home *** CD-ROM | disk | FTP | other *** search
/ Aminet 48 / Aminet 48 (2002)(GTI - Schatztruhe)[!][Apr 2002].iso / Aminet / text / edit / vim60src.lha / Vim / vim60 / src / regexp.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-09-07  |  128.1 KB  |  5,721 lines

  1. /* vi:set ts=8 sts=4 sw=4:
  2.  *
  3.  * Handling of regular expressions: vim_regcomp(), vim_regexec(), vim_regsub()
  4.  *
  5.  * NOTICE:
  6.  *
  7.  * This is NOT the original regular expression code as written by Henry
  8.  * Spencer.  This code has been modified specifically for use with the VIM
  9.  * editor, and should not be used separately from Vim.  If you want a good
  10.  * regular expression library, get the original code.  The copyright notice
  11.  * that follows is from the original.
  12.  *
  13.  * END NOTICE
  14.  *
  15.  *    Copyright (c) 1986 by University of Toronto.
  16.  *    Written by Henry Spencer.  Not derived from licensed software.
  17.  *
  18.  *    Permission is granted to anyone to use this software for any
  19.  *    purpose on any computer system, and to redistribute it freely,
  20.  *    subject to the following restrictions:
  21.  *
  22.  *    1. The author is not responsible for the consequences of use of
  23.  *        this software, no matter how awful, even if they arise
  24.  *        from defects in it.
  25.  *
  26.  *    2. The origin of this software must not be misrepresented, either
  27.  *        by explicit claim or by omission.
  28.  *
  29.  *    3. Altered versions must be plainly marked as such, and must not
  30.  *        be misrepresented as being the original software.
  31.  *
  32.  * Beware that some of this code is subtly aware of the way operator
  33.  * precedence is structured in regular expressions.  Serious changes in
  34.  * regular-expression syntax might require a total rethink.
  35.  *
  36.  * Changes have been made by Tony Andrews, Olaf 'Rhialto' Seibert, Robert Webb
  37.  * and Bram Moolenaar.
  38.  * Named character class support added by Walter Briscoe (1998 Jul 01)
  39.  */
  40.  
  41. #include "vim.h"
  42.  
  43. #undef DEBUG
  44.  
  45. /*
  46.  * The "internal use only" fields in regexp.h are present to pass info from
  47.  * compile to execute that permits the execute phase to run lots faster on
  48.  * simple cases.  They are:
  49.  *
  50.  * regstart    char that must begin a match; NUL if none obvious; Can be a
  51.  *        multi-byte character.
  52.  * reganch    is the match anchored (at beginning-of-line only)?
  53.  * regmust    string (pointer into program) that match must include, or NULL
  54.  * regmlen    length of regmust string
  55.  * regflags    RF_ values or'ed together
  56.  *
  57.  * Regstart and reganch permit very fast decisions on suitable starting points
  58.  * for a match, cutting down the work a lot.  Regmust permits fast rejection
  59.  * of lines that cannot possibly match.  The regmust tests are costly enough
  60.  * that vim_regcomp() supplies a regmust only if the r.e. contains something
  61.  * potentially expensive (at present, the only such thing detected is * or +
  62.  * at the start of the r.e., which can involve a lot of backup).  Regmlen is
  63.  * supplied because the test in vim_regexec() needs it and vim_regcomp() is
  64.  * computing it anyway.
  65.  */
  66.  
  67. /*
  68.  * Structure for regexp "program".  This is essentially a linear encoding
  69.  * of a nondeterministic finite-state machine (aka syntax charts or
  70.  * "railroad normal form" in parsing technology).  Each node is an opcode
  71.  * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
  72.  * all nodes except BRANCH and BRACES_COMPLEX implement concatenation; a "next"
  73.  * pointer with a BRANCH on both ends of it is connecting two alternatives.
  74.  * (Here we have one of the subtle syntax dependencies:    an individual BRANCH
  75.  * (as opposed to a collection of them) is never concatenated with anything
  76.  * because of operator precedence).  The "next" pointer of a BRACES_COMPLEX
  77.  * node points to the node after the stuff to be repeated.  The operand of some
  78.  * types of node is a literal string; for others, it is a node leading into a
  79.  * sub-FSM.  In particular, the operand of a BRANCH node is the first node of
  80.  * the branch.    (NB this is *not* a tree structure: the tail of the branch
  81.  * connects to the thing following the set of BRANCHes.)
  82.  *
  83.  * pattern    is coded like:
  84.  *
  85.  *              +-----------------+
  86.  *              |            V
  87.  * <aa>\|<bb>    BRANCH <aa> BRANCH <bb> --> END
  88.  *             |        ^     |        ^
  89.  *             +------+     +----------+
  90.  *
  91.  *
  92.  *               +------------------+
  93.  *               V          |
  94.  * <aa>*    BRANCH BRANCH <aa> --> BACK BRANCH --> NOTHING --> END
  95.  *             |        |            ^               ^
  96.  *             |        +---------------+               |
  97.  *             +---------------------------------------------+
  98.  *
  99.  *
  100.  *                    +-------------------------+
  101.  *                    V              |
  102.  * <aa>\{}    BRANCH BRACE_LIMITS --> BRACE_COMPLEX <aa> --> BACK  END
  103.  *             |                    |             ^
  104.  *             |                    +----------------+
  105.  *             +-----------------------------------------------+
  106.  *
  107.  *
  108.  * <aa>\@!<bb>    BRANCH NOMATCH <aa> --> END  <bb> --> END
  109.  *             |         |              ^       ^
  110.  *             |         +----------------+       |
  111.  *             +--------------------------------+
  112.  *
  113.  *                              +---------+
  114.  *                              |        V
  115.  * \z[abc]    BRANCH BRANCH  a  BRANCH  b  BRANCH  c    BRANCH    NOTHING --> END
  116.  *             |        |           |      |    ^            ^
  117.  *             |        |           |      +-----+            |
  118.  *             |        |           +----------------+            |
  119.  *             |        +---------------------------+            |
  120.  *             +------------------------------------------------------+
  121.  *
  122.  * They all start with a BRANCH for "\|" alternaties, even when there is only
  123.  * one alternative.
  124.  */
  125.  
  126. /*
  127.  * The opcodes are:
  128.  */
  129.  
  130. /* definition    number           opnd?    meaning */
  131. #define END        0    /*    End of program or NOMATCH operand. */
  132. #define BOL        1    /*    Match "" at beginning of line. */
  133. #define EOL        2    /*    Match "" at end of line. */
  134. #define BRANCH        3    /* node Match this alternative, or the
  135.                  *    next... */
  136. #define BACK        4    /*    Match "", "next" ptr points backward. */
  137. #define EXACTLY        5    /* str    Match this string. */
  138. #define NOTHING        6    /*    Match empty string. */
  139. #define STAR        7    /* node Match this (simple) thing 0 or more
  140.                  *    times. */
  141. #define PLUS        8    /* node Match this (simple) thing 1 or more
  142.                  *    times. */
  143. #define MATCH        9    /* node match the operand zero-width */
  144. #define NOMATCH        10    /* node check for no match with operand */
  145. #define BEHIND        11    /* node look behind for a match with operand */
  146. #define NOBEHIND    12    /* node look behind for no match with operand */
  147. #define SUBPAT        13    /* node match the operand here */
  148. #define BRACE_SIMPLE    14    /* node Match this (simple) thing between m and
  149.                  *    n times (\{m,n\}). */
  150. #define BOW        15    /*    Match "" after [^a-zA-Z0-9_] */
  151. #define EOW        16    /*    Match "" at    [^a-zA-Z0-9_] */
  152. #define BRACE_LIMITS    17    /* nr nr  define the min & max for BRACE_SIMPLE
  153.                  *    and BRACE_COMPLEX. */
  154. #define NEWL        18    /*    Match line-break */
  155. #define BHPOS        19    /*    End position for BEHIND or NOBEHIND */
  156.  
  157.  
  158. /* character classes: 20-48 normal, 50-78 include a line-break */
  159. #define ADD_NL        30
  160. #define FIRST_NL    ANY + ADD_NL
  161. #define ANY        20    /*    Match any one character. */
  162. #define ANYOF        21    /* str    Match any character in this string. */
  163. #define ANYBUT        22    /* str    Match any character not in this
  164.                  *    string. */
  165. #define IDENT        23    /*    Match identifier char */
  166. #define SIDENT        24    /*    Match identifier char but no digit */
  167. #define KWORD        25    /*    Match keyword char */
  168. #define SKWORD        26    /*    Match word char but no digit */
  169. #define FNAME        27    /*    Match file name char */
  170. #define SFNAME        28    /*    Match file name char but no digit */
  171. #define PRINT        29    /*    Match printable char */
  172. #define SPRINT        30    /*    Match printable char but no digit */
  173. #define WHITE        31    /*    Match whitespace char */
  174. #define NWHITE        32    /*    Match non-whitespace char */
  175. #define DIGIT        33    /*    Match digit char */
  176. #define NDIGIT        34    /*    Match non-digit char */
  177. #define HEX        35    /*    Match hex char */
  178. #define NHEX        36    /*    Match non-hex char */
  179. #define OCTAL        37    /*    Match octal char */
  180. #define NOCTAL        38    /*    Match non-octal char */
  181. #define WORD        39    /*    Match word char */
  182. #define NWORD        40    /*    Match non-word char */
  183. #define HEAD        41    /*    Match head char */
  184. #define NHEAD        42    /*    Match non-head char */
  185. #define ALPHA        43    /*    Match alpha char */
  186. #define NALPHA        44    /*    Match non-alpha char */
  187. #define LOWER        45    /*    Match lowercase char */
  188. #define NLOWER        46    /*    Match non-lowercase char */
  189. #define UPPER        47    /*    Match uppercase char */
  190. #define NUPPER        48    /*    Match non-uppercase char */
  191. #define LAST_NL        NUPPER + ADD_NL
  192. #define WITH_NL(op)    ((op) >= FIRST_NL && (op) <= LAST_NL)
  193.  
  194. #define MOPEN        80  /* -89     Mark this point in input as start of
  195.                  *     \( subexpr.  MOPEN + 0 marks start of
  196.                  *     match. */
  197. #define MCLOSE        90  /* -99     Analogous to MOPEN.  MCLOSE + 0 marks
  198.                  *     end of match. */
  199. #define BACKREF        100 /* -109 node Match same string again \1-\9 */
  200.  
  201. #ifdef FEAT_SYN_HL
  202. # define ZOPEN        110 /* -119     Mark this point in input as start of
  203.                  *     \z( subexpr. */
  204. # define ZCLOSE        120 /* -129     Analogous to ZOPEN. */
  205. # define ZREF        130 /* -139 node Match external submatch \z1-\z9 */
  206. #endif
  207.  
  208. #define BRACE_COMPLEX    140 /* -149 node Match nodes between m & n times */
  209.  
  210. #define NOPEN        150    /*    Mark this point in input as start of
  211.                     \%( subexpr. */
  212. #define NCLOSE        151    /*    Analogous to NOPEN. */
  213.  
  214. #define MULTIBYTECODE    200    /* mbc    Match one multi-byte character */
  215. #define RE_BOF        201    /*    Match "" at beginning of file. */
  216. #define RE_EOF        202    /*    Match "" at end of file. */
  217. #define CURSOR        203    /*    Match location of cursor. */
  218.  
  219. #define RE_LNUM        204    /* nr cmp  Match line number */
  220. #define RE_COL        205    /* nr cmp  Match column number */
  221. #define RE_VCOL        206    /* nr cmp  Match virtual column number */
  222.  
  223. /*
  224.  * Magic characters have a special meaning, they don't match literally.
  225.  * Magic characters are negative.  This separates them from literal characters
  226.  * (possibly multi-byte).  Only ASCII characters can be Magic.
  227.  */
  228. #define Magic(x)    ((int)(x) - 256)
  229. #define un_Magic(x)    ((x) + 256)
  230. #define is_Magic(x)    ((x) < 0)
  231.  
  232. static int no_Magic __ARGS((int x));
  233. static int toggle_Magic __ARGS((int x));
  234.  
  235.     static int
  236. no_Magic(x)
  237.     int        x;
  238. {
  239.     if (is_Magic(x))
  240.     return un_Magic(x);
  241.     return x;
  242. }
  243.  
  244.     static int
  245. toggle_Magic(x)
  246.     int        x;
  247. {
  248.     if (is_Magic(x))
  249.     return un_Magic(x);
  250.     return Magic(x);
  251. }
  252.  
  253. /*
  254.  * The first byte of the regexp internal "program" is actually this magic
  255.  * number; the start node begins in the second byte.  It's used to catch the
  256.  * most severe mutilation of the program by the caller.
  257.  */
  258.  
  259. #define REGMAGIC    0234
  260.  
  261. /*
  262.  * Opcode notes:
  263.  *
  264.  * BRANCH    The set of branches constituting a single choice are hooked
  265.  *        together with their "next" pointers, since precedence prevents
  266.  *        anything being concatenated to any individual branch.  The
  267.  *        "next" pointer of the last BRANCH in a choice points to the
  268.  *        thing following the whole choice.  This is also where the
  269.  *        final "next" pointer of each individual branch points; each
  270.  *        branch starts with the operand node of a BRANCH node.
  271.  *
  272.  * BACK        Normal "next" pointers all implicitly point forward; BACK
  273.  *        exists to make loop structures possible.
  274.  *
  275.  * STAR,PLUS    '=', and complex '*' and '+', are implemented as circular
  276.  *        BRANCH structures using BACK.  Simple cases (one character
  277.  *        per match) are implemented with STAR and PLUS for speed
  278.  *        and to minimize recursive plunges.
  279.  *
  280.  * BRACE_LIMITS    This is always followed by a BRACE_SIMPLE or BRACE_COMPLEX
  281.  *        node, and defines the min and max limits to be used for that
  282.  *        node.
  283.  *
  284.  * MOPEN,MCLOSE    ...are numbered at compile time.
  285.  * ZOPEN,ZCLOSE    ...ditto
  286.  */
  287.  
  288. /*
  289.  * A node is one char of opcode followed by two chars of "next" pointer.
  290.  * "Next" pointers are stored as two 8-bit bytes, high order first.  The
  291.  * value is a positive offset from the opcode of the node containing it.
  292.  * An operand, if any, simply follows the node.  (Note that much of the
  293.  * code generation knows about this implicit relationship.)
  294.  *
  295.  * Using two bytes for the "next" pointer is vast overkill for most things,
  296.  * but allows patterns to get big without disasters.
  297.  */
  298. #define OP(p)        ((int)*(p))
  299. #define NEXT(p)        (((*((p) + 1) & 0377) << 8) + (*((p) + 2) & 0377))
  300. #define OPERAND(p)    ((p) + 3)
  301. /* Obtain an operand that was stored as four bytes, MSB first. */
  302. #define OPERAND_MIN(p)    (((long)(p)[3] << 24) + ((long)(p)[4] << 16) \
  303.             + ((long)(p)[5] << 8) + (long)(p)[6])
  304. /* Obtain a second operand stored as four bytes. */
  305. #define OPERAND_MAX(p)    OPERAND_MIN((p) + 4)
  306. /* Obtain a second single-byte operand stored after a four bytes operand. */
  307. #define OPERAND_CMP(p)    (p)[7]
  308.  
  309. /*
  310.  * Utility definitions.
  311.  */
  312. #define UCHARAT(p)    ((int)*(char_u *)(p))
  313.  
  314. /* Used for an error (down from) vim_regcomp(): give the error message, set
  315.  * rc_did_emsg and return NULL */
  316. #define EMSG_RET_NULL(m) { EMSG(_(m)); rc_did_emsg = TRUE; return NULL; }
  317. #define EMSG_M_RET_NULL(m, c) { EMSG2(_(m), c ? "" : "\\"); rc_did_emsg = TRUE; return NULL; }
  318. #define EMSG_RET_FAIL(m) { EMSG(_(m)); rc_did_emsg = TRUE; return FAIL; }
  319.  
  320. #define MAX_LIMIT    (32767L << 16L)
  321.  
  322. static int re_multi_type __ARGS((int));
  323. static int cstrncmp __ARGS((char_u *s1, char_u *s2, int n));
  324. static char_u *cstrchr __ARGS((char_u *, int));
  325.  
  326. #ifdef DEBUG
  327. static void    regdump __ARGS((char_u *, regprog_T *));
  328. static char_u    *regprop __ARGS((char_u *));
  329. #endif
  330.  
  331. #define NOT_MULTI    0
  332. #define MULTI_ONE    1
  333. #define MULTI_MULT    2
  334. /*
  335.  * Return NOT_MULTI if c is not a "multi" operator.
  336.  * Return MULTI_ONE if c is a single "multi" operator.
  337.  * Return MULTI_MULT if c is a multi "multi" operator.
  338.  */
  339.     static int
  340. re_multi_type(c)
  341.     int c;
  342. {
  343.     if (c == Magic('@') || c == Magic('=') || c == Magic('?'))
  344.     return MULTI_ONE;
  345.     if (c == Magic('*') || c == Magic('+') || c == Magic('{'))
  346.     return MULTI_MULT;
  347.     return NOT_MULTI;
  348. }
  349.  
  350. /*
  351.  * Flags to be passed up and down.
  352.  */
  353. #define HASWIDTH    0x1    /* Known never to match null string. */
  354. #define SIMPLE        0x2    /* Simple enough to be STAR/PLUS operand. */
  355. #define SPSTART        0x4    /* Starts with * or +. */
  356. #define HASNL        0x8    /* Contains some \n. */
  357. #define WORST        0    /* Worst case. */
  358.  
  359. /*
  360.  * When regcode is set to this value, code is not emitted and size is computed
  361.  * instead.
  362.  */
  363. #define JUST_CALC_SIZE    ((char_u *) -1)
  364.  
  365. static char_u        *reg_prev_sub;
  366.  
  367. /*
  368.  * REGEXP_INRANGE contains all characters which are always special in a []
  369.  * range after '\'.
  370.  * REGEXP_ABBR contains all characters which act as abbreviations after '\'.
  371.  * These are:
  372.  *  \n    - New line (NL).
  373.  *  \r    - Carriage Return (CR).
  374.  *  \t    - Tab (TAB).
  375.  *  \e    - Escape (ESC).
  376.  *  \b    - Backspace (Ctrl_H).
  377.  */
  378. static char_u REGEXP_INRANGE[] = "]^-n\\";
  379. static char_u REGEXP_ABBR[] = "nrteb";
  380.  
  381. static int    backslash_trans __ARGS((int c));
  382. static int    skip_class_name __ARGS((char_u **pp));
  383. static char_u    *skip_anyof __ARGS((char_u *p));
  384. static void    init_class_tab __ARGS((void));
  385.  
  386. /*
  387.  * Translate '\x' to its control character, except "\n", which is Magic.
  388.  */
  389.     static int
  390. backslash_trans(c)
  391.     int        c;
  392. {
  393.     switch (c)
  394.     {
  395.     case 'r':   return CR;
  396.     case 't':   return TAB;
  397.     case 'e':   return ESC;
  398.     case 'b':   return BS;
  399.     }
  400.     return c;
  401. }
  402.  
  403. /*
  404.  * Check for a character class name.  "pp" points to the '['.
  405.  * Returns one of the CLASS_ items. CLASS_NONE means that no item was
  406.  * recognized.  Otherwise "pp" is advanced to after the item.
  407.  */
  408.     static int
  409. skip_class_name(pp)
  410.     char_u    **pp;
  411. {
  412.     static const char *(class_names[]) =
  413.     {
  414.     "alnum:]",
  415. #define CLASS_ALNUM 0
  416.     "alpha:]",
  417. #define CLASS_ALPHA 1
  418.     "blank:]",
  419. #define CLASS_BLANK 2
  420.     "cntrl:]",
  421. #define CLASS_CNTRL 3
  422.     "digit:]",
  423. #define CLASS_DIGIT 4
  424.     "graph:]",
  425. #define CLASS_GRAPH 5
  426.     "lower:]",
  427. #define CLASS_LOWER 6
  428.     "print:]",
  429. #define CLASS_PRINT 7
  430.     "punct:]",
  431. #define CLASS_PUNCT 8
  432.     "space:]",
  433. #define CLASS_SPACE 9
  434.     "upper:]",
  435. #define CLASS_UPPER 10
  436.     "xdigit:]",
  437. #define CLASS_XDIGIT 11
  438.     "tab:]",
  439. #define CLASS_TAB 12
  440.     "return:]",
  441. #define CLASS_RETURN 13
  442.     "backspace:]",
  443. #define CLASS_BACKSPACE 14
  444.     "escape:]",
  445. #define CLASS_ESCAPE 15
  446.     };
  447. #define CLASS_NONE 99
  448.     int i;
  449.  
  450.     if ((*pp)[1] == ':')
  451.     {
  452.     for (i = 0; i < sizeof(class_names) / sizeof(*class_names); ++i)
  453.         if (STRNCMP(*pp + 2, class_names[i], STRLEN(class_names[i])) == 0)
  454.         {
  455.         *pp += STRLEN(class_names[i]) + 2;
  456.         return i;
  457.         }
  458.     }
  459.     return CLASS_NONE;
  460. }
  461.  
  462. /*
  463.  * Skip over a "[]" range.
  464.  * "p" must point to the character after the '['.
  465.  * The returned pointer is on the matching ']', or the terminating NUL.
  466.  */
  467.     static char_u *
  468. skip_anyof(p)
  469.     char_u    *p;
  470. {
  471.     int        cpo_lit;    /* 'cpoptions' contains 'l' flag */
  472. #ifdef FEAT_MBYTE
  473.     int        l;
  474. #endif
  475.  
  476.     cpo_lit = (!reg_syn && vim_strchr(p_cpo, CPO_LITERAL) != NULL);
  477.  
  478.     if (*p == '^')    /* Complement of range. */
  479.     ++p;
  480.     if (*p == ']' || *p == '-')
  481.     ++p;
  482.     while (*p != NUL && *p != ']')
  483.     {
  484. #ifdef FEAT_MBYTE
  485.     if (has_mbyte && (l = (*mb_ptr2len_check)(p)) > 1)
  486.         p += l;
  487.     else
  488. #endif
  489.         if (*p == '-')
  490.         {
  491.         ++p;
  492.         if (*p != ']' && *p != NUL)
  493.         {
  494. #ifdef FEAT_MBYTE
  495.             if (has_mbyte)
  496.             p += (*mb_ptr2len_check)(p);
  497.             else
  498. #endif
  499.             ++p;
  500.         }
  501.         }
  502.     else if (*p == '\\'
  503.         && (vim_strchr(REGEXP_INRANGE, p[1]) != NULL
  504.             || (!cpo_lit && vim_strchr(REGEXP_ABBR, p[1]) != NULL)))
  505.         p += 2;
  506.     else if (*p == '[')
  507.     {
  508.         if (skip_class_name(&p) == CLASS_NONE)
  509.         ++p; /* It was not a class name */
  510.     }
  511.     else
  512.         ++p;
  513.     }
  514.  
  515.     return p;
  516. }
  517.  
  518. /*
  519.  * Specific version of character class functions.
  520.  * Using a table to keep this fast.
  521.  */
  522. static short    class_tab[256];
  523.  
  524. #define        RI_DIGIT    0x01
  525. #define        RI_HEX    0x02
  526. #define        RI_OCTAL    0x04
  527. #define        RI_WORD    0x08
  528. #define        RI_HEAD    0x10
  529. #define        RI_ALPHA    0x20
  530. #define        RI_LOWER    0x40
  531. #define        RI_UPPER    0x80
  532. #define        RI_WHITE    0x100
  533.  
  534.     static void
  535. init_class_tab()
  536. {
  537.     int        i;
  538.     static int    done = FALSE;
  539.  
  540.     if (done)
  541.     return;
  542.  
  543.     for (i = 0; i < 256; ++i)
  544.     {
  545.     if (i >= '0' && i <= '7')
  546.         class_tab[i] = RI_DIGIT + RI_HEX + RI_OCTAL + RI_WORD;
  547.     else if (i >= '8' && i <= '9')
  548.         class_tab[i] = RI_DIGIT + RI_HEX + RI_WORD;
  549.     else if (i >= 'a' && i <= 'f')
  550.         class_tab[i] = RI_HEX + RI_WORD + RI_HEAD + RI_ALPHA + RI_LOWER;
  551. #ifdef EBCDIC
  552.     else if ((i >= 'g' && i <= 'i') || (i >= 'j' && i <= 'r')
  553.                             || (i >= 's' && i <= 'z'))
  554. #else
  555.     else if (i >= 'g' && i <= 'z')
  556. #endif
  557.         class_tab[i] = RI_WORD + RI_HEAD + RI_ALPHA + RI_LOWER;
  558.     else if (i >= 'A' && i <= 'F')
  559.         class_tab[i] = RI_HEX + RI_WORD + RI_HEAD + RI_ALPHA + RI_UPPER;
  560. #ifdef EBCDIC
  561.     else if ((i >= 'G' && i <= 'I') || ( i >= 'J' && i <= 'R')
  562.                             || (i >= 'S' && i <= 'Z'))
  563. #else
  564.     else if (i >= 'G' && i <= 'Z')
  565. #endif
  566.         class_tab[i] = RI_WORD + RI_HEAD + RI_ALPHA + RI_UPPER;
  567.     else if (i == '_')
  568.         class_tab[i] = RI_WORD + RI_HEAD;
  569.     else
  570.         class_tab[i] = 0;
  571.     }
  572.     class_tab[' '] |= RI_WHITE;
  573.     class_tab['\t'] |= RI_WHITE;
  574.     done = TRUE;
  575. }
  576.  
  577. #ifdef FEAT_MBYTE
  578. # define ri_digit(c)    (c < 0x100 && (class_tab[c] & RI_DIGIT))
  579. # define ri_hex(c)    (c < 0x100 && (class_tab[c] & RI_HEX))
  580. # define ri_octal(c)    (c < 0x100 && (class_tab[c] & RI_OCTAL))
  581. # define ri_word(c)    (c < 0x100 && (class_tab[c] & RI_WORD))
  582. # define ri_head(c)    (c < 0x100 && (class_tab[c] & RI_HEAD))
  583. # define ri_alpha(c)    (c < 0x100 && (class_tab[c] & RI_ALPHA))
  584. # define ri_lower(c)    (c < 0x100 && (class_tab[c] & RI_LOWER))
  585. # define ri_upper(c)    (c < 0x100 && (class_tab[c] & RI_UPPER))
  586. # define ri_white(c)    (c < 0x100 && (class_tab[c] & RI_WHITE))
  587. #else
  588. # define ri_digit(c)    (class_tab[c] & RI_DIGIT)
  589. # define ri_hex(c)    (class_tab[c] & RI_HEX)
  590. # define ri_octal(c)    (class_tab[c] & RI_OCTAL)
  591. # define ri_word(c)    (class_tab[c] & RI_WORD)
  592. # define ri_head(c)    (class_tab[c] & RI_HEAD)
  593. # define ri_alpha(c)    (class_tab[c] & RI_ALPHA)
  594. # define ri_lower(c)    (class_tab[c] & RI_LOWER)
  595. # define ri_upper(c)    (class_tab[c] & RI_UPPER)
  596. # define ri_white(c)    (class_tab[c] & RI_WHITE)
  597. #endif
  598.  
  599. /* flags for regflags */
  600. #define RF_ICASE    1    /* ignore case */
  601. #define RF_NOICASE  2    /* don't ignore case */
  602. #define RF_HASNL    4    /* can match a NL */
  603.  
  604. /*
  605.  * Global work variables for vim_regcomp().
  606.  */
  607.  
  608. static char_u    *regparse;    /* Input-scan pointer. */
  609. static int    prevchr_len;    /* byte length of previous char */
  610. static int    num_complex_braces; /* Complex \{...} count */
  611. static int    regnpar;    /* () count. */
  612. #ifdef FEAT_SYN_HL
  613. static int    regnzpar;    /* \z() count. */
  614. static int    re_has_z;    /* \z item detected */
  615. #endif
  616. static char_u    *regcode;    /* Code-emit pointer, or JUST_CALC_SIZE */
  617. static long    regsize;    /* Code size. */
  618. static char_u    had_endbrace[NSUBEXP];    /* flags, TRUE if end of () found */
  619. static unsigned    regflags;    /* RF_ flags for prog */
  620. static long    brace_min[10];    /* Minimums for complex brace repeats */
  621. static long    brace_max[10];    /* Maximums for complex brace repeats */
  622. static int    brace_count[10]; /* Current counts for complex brace repeats */
  623. #if defined(FEAT_SYN_HL) || defined(PROTO)
  624. static int    had_eol;    /* TRUE when EOL found by vim_regcomp() */
  625. #endif
  626. static int    one_exactly = FALSE;    /* only do one char for EXACTLY */
  627.  
  628. static int    reg_magic;    /* magicness of the pattern: */
  629. #define MAGIC_NONE    1    /* "\V" very unmagic */
  630. #define MAGIC_OFF    2    /* "\M" or 'magic' off */
  631. #define MAGIC_ON    3    /* "\m" or 'magic' */
  632. #define MAGIC_ALL    4    /* "\v" very magic */
  633.  
  634. /*
  635.  * META contains all characters that may be magic, except '^' and '$'.
  636.  */
  637.  
  638. #ifdef EBCDIC
  639. static char_u META[] = "%&()*+.123456789<=>?@ACDFHIKLMOPSUVWX[_acdfhiklmnopsuvwxz{|~";
  640. #else
  641. /* META[] is used often enough to justify turning it into a table. */
  642. static char_u META_flags[] = {
  643.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  644.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  645. /*           %  &     (  )  *  +          .    */
  646.     0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0,
  647. /*     1  2  3    4  5  6  7  8  9    <  =  >  ? */
  648.     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1,
  649. /*  @  A     C    D     F     H  I     K    L  M     O */
  650.     1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1,
  651. /*  P         S       U  V  W  X         [         _ */
  652.     1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1,
  653. /*     a     c    d     f     h  i     k    l  m  n  o */
  654.     0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1,
  655. /*  p         s       u  v  w  x      z  {    |     ~    */
  656.     1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1
  657. };
  658. #endif
  659.  
  660. static int    curchr;
  661.  
  662. /* arguments for reg() */
  663. #define REG_NOPAREN    0    /* toplevel reg() */
  664. #define REG_PAREN    1    /* \(\) */
  665. #define REG_ZPAREN    2    /* \z(\) */
  666. #define REG_NPAREN    3    /* \%(\) */
  667.  
  668. /*
  669.  * Forward declarations for vim_regcomp()'s friends.
  670.  */
  671. static void    initchr __ARGS((char_u *));
  672. static int    getchr __ARGS((void));
  673. static void    skipchr_keepstart __ARGS((void));
  674. static int    peekchr __ARGS((void));
  675. static void    skipchr __ARGS((void));
  676. static void    ungetchr __ARGS((void));
  677. static void    regcomp_start __ARGS((char_u *expr, int magic));
  678. static char_u    *reg __ARGS((int, int *));
  679. static char_u    *regbranch __ARGS((int *flagp));
  680. static char_u    *regconcat __ARGS((int *flagp));
  681. static char_u    *regpiece __ARGS((int *));
  682. static char_u    *regatom __ARGS((int *));
  683. static char_u    *regnode __ARGS((int));
  684. static int    prog_magic_wrong __ARGS((void));
  685. static char_u    *regnext __ARGS((char_u *));
  686. static void    regc __ARGS((int b));
  687. #ifdef FEAT_MBYTE
  688. static void    regmbc __ARGS((int c));
  689. #endif
  690. static void    reginsert __ARGS((int, char_u *));
  691. static void    reginsert_limits __ARGS((int, long, long, char_u *));
  692. static char_u    *re_put_long __ARGS((char_u *pr, long_u val));
  693. static int    read_limits __ARGS((long *, long *));
  694. static void    regtail __ARGS((char_u *, char_u *));
  695. static void    regoptail __ARGS((char_u *, char_u *));
  696.  
  697. #if defined(FEAT_SEARCH_EXTRA) || defined(PROTO)
  698. /*
  699.  * Return TRUE if compiled regular expression "prog" can match a line break.
  700.  */
  701.     int
  702. re_multiline(prog)
  703.     regprog_T *prog;
  704. {
  705.     return (prog->regflags & RF_HASNL);
  706. }
  707. #endif
  708.  
  709. /*
  710.  * Skip past regular expression.
  711.  * Stop at end of 'p' of where 'dirc' is found ('/', '?', etc).
  712.  * Take care of characters with a backslash in front of it.
  713.  * Skip strings inside [ and ].
  714.  */
  715.     char_u *
  716. skip_regexp(p, dirc, magic)
  717.     char_u    *p;
  718.     int        dirc;
  719.     int        magic;
  720. {
  721.     int        mymagic;
  722.  
  723.     if (magic)
  724.     mymagic = MAGIC_ON;
  725.     else
  726.     mymagic = MAGIC_OFF;
  727.  
  728.     for (; p[0] != NUL; ++p)
  729.     {
  730.     if (p[0] == dirc)    /* found end of regexp */
  731.         break;
  732.     if ((p[0] == '[' && mymagic >= MAGIC_ON)
  733.         || (p[0] == '\\' && p[1] == '[' && mymagic <= MAGIC_OFF))
  734.     {
  735.         p = skip_anyof(p + 1);
  736.         if (p[0] == NUL)
  737.         break;
  738.     }
  739.     else if (p[0] == '\\' && p[1] != NUL)
  740.     {
  741.         ++p;    /* skip next character */
  742.         if (*p == 'v')
  743.         mymagic = MAGIC_ALL;
  744.         else if (*p == 'V')
  745.         mymagic = MAGIC_NONE;
  746.     }
  747. #ifdef FEAT_MBYTE
  748.     else if (has_mbyte)
  749.         p += (*mb_ptr2len_check)(p) - 1;
  750. #endif
  751.     }
  752.     return p;
  753. }
  754.  
  755. /*
  756.  * vim_regcomp - compile a regular expression into internal code
  757.  *
  758.  * We can't allocate space until we know how big the compiled form will be,
  759.  * but we can't compile it (and thus know how big it is) until we've got a
  760.  * place to put the code.  So we cheat:  we compile it twice, once with code
  761.  * generation turned off and size counting turned on, and once "for real".
  762.  * This also means that we don't allocate space until we are sure that the
  763.  * thing really will compile successfully, and we never have to move the
  764.  * code and thus invalidate pointers into it.  (Note that it has to be in
  765.  * one piece because vim_free() must be able to free it all.)
  766.  *
  767.  * Whether upper/lower case is to be ignored is decided when executing the
  768.  * program, it does not matter here.
  769.  *
  770.  * Beware that the optimization-preparation code in here knows about some
  771.  * of the structure of the compiled regexp.
  772.  */
  773.     regprog_T *
  774. vim_regcomp(expr, magic)
  775.     char_u    *expr;
  776.     int        magic;
  777. {
  778.     regprog_T    *r;
  779.     char_u    *scan;
  780.     char_u    *longest;
  781.     int        len;
  782.     int        flags;
  783.  
  784.     if (expr == NULL)
  785.     EMSG_RET_NULL(e_null);
  786.  
  787.     init_class_tab();
  788.  
  789.     /*
  790.      * First pass: determine size, legality.
  791.      */
  792.     regcomp_start(expr, magic);
  793.     regcode = JUST_CALC_SIZE;
  794.     regc(REGMAGIC);
  795.     if (reg(REG_NOPAREN, &flags) == NULL)
  796.     return NULL;
  797.  
  798.     /* Small enough for pointer-storage convention? */
  799. #ifdef SMALL_MALLOC        /* 16 bit storage allocation */
  800.     if (regsize >= 65536L - 256L)
  801.     EMSG_RET_NULL(N_("E339: Pattern too long"));
  802. #endif
  803.  
  804.     /* Allocate space. */
  805.     r = (regprog_T *)lalloc(sizeof(regprog_T) + regsize, TRUE);
  806.     if (r == NULL)
  807.     return NULL;
  808.  
  809.     /*
  810.      * Second pass: emit code.
  811.      */
  812.     regcomp_start(expr, magic);
  813.     regcode = r->program;
  814.     regc(REGMAGIC);
  815.     if (reg(REG_NOPAREN, &flags) == NULL)
  816.     {
  817.     vim_free(r);
  818.     return NULL;
  819.     }
  820.  
  821.     /* Dig out information for optimizations. */
  822.     r->regstart = NUL;        /* Worst-case defaults. */
  823.     r->reganch = 0;
  824.     r->regmust = NULL;
  825.     r->regmlen = 0;
  826.     r->regflags = regflags;
  827.     if (flags & HASNL)
  828.     r->regflags |= RF_HASNL;
  829. #ifdef FEAT_SYN_HL
  830.     /* Remember whether this pattern has any \z specials in it. */
  831.     r->reghasz = re_has_z;
  832. #endif
  833.     scan = r->program + 1;    /* First BRANCH. */
  834.     if (OP(regnext(scan)) == END)   /* Only one top-level choice. */
  835.     {
  836.     scan = OPERAND(scan);
  837.  
  838.     /* Starting-point info. */
  839.     if (OP(scan) == BOL || OP(scan) == RE_BOF)
  840.     {
  841.         r->reganch++;
  842.         scan = regnext(scan);
  843.     }
  844.  
  845.     if (OP(scan) == EXACTLY)
  846.     {
  847. #ifdef FEAT_MBYTE
  848.         if (has_mbyte)
  849.         r->regstart = (*mb_ptr2char)(OPERAND(scan));
  850.         else
  851. #endif
  852.         r->regstart = *OPERAND(scan);
  853.     }
  854.     else if ((OP(scan) == BOW
  855.             || OP(scan) == EOW
  856.             || OP(scan) == NOTHING
  857.             || OP(scan) == MOPEN + 0 || OP(scan) == NOPEN
  858.             || OP(scan) == MCLOSE + 0 || OP(scan) == NCLOSE)
  859.          && OP(regnext(scan)) == EXACTLY)
  860.     {
  861. #ifdef FEAT_MBYTE
  862.         if (has_mbyte)
  863.         r->regstart = (*mb_ptr2char)(OPERAND(regnext(scan)));
  864.         else
  865. #endif
  866.         r->regstart = *OPERAND(regnext(scan));
  867.     }
  868.  
  869.     /*
  870.      * If there's something expensive in the r.e., find the longest
  871.      * literal string that must appear and make it the regmust.  Resolve
  872.      * ties in favor of later strings, since the regstart check works
  873.      * with the beginning of the r.e. and avoiding duplication
  874.      * strengthens checking.  Not a strong reason, but sufficient in the
  875.      * absence of others.
  876.      */
  877.     /*
  878.      * When the r.e. starts with BOW, it is faster to look for a regmust
  879.      * first. Used a lot for "#" and "*" commands. (Added by mool).
  880.      */
  881.     if ((flags & SPSTART || OP(scan) == BOW || OP(scan) == EOW)
  882.                               && !(flags & HASNL))
  883.     {
  884.         longest = NULL;
  885.         len = 0;
  886.         for (; scan != NULL; scan = regnext(scan))
  887.         if (OP(scan) == EXACTLY && STRLEN(OPERAND(scan)) >= (size_t)len)
  888.         {
  889.             longest = OPERAND(scan);
  890.             len = (int)STRLEN(OPERAND(scan));
  891.         }
  892.         r->regmust = longest;
  893.         r->regmlen = len;
  894.     }
  895.     }
  896. #ifdef DEBUG
  897.     regdump(expr, r);
  898. #endif
  899.     return r;
  900. }
  901.  
  902. /*
  903.  * Setup to parse the regexp.  Used once to get the length and once to do it.
  904.  */
  905.     static void
  906. regcomp_start(expr, magic)
  907.     char_u    *expr;
  908.     int        magic;
  909. {
  910.     initchr(expr);
  911.     if (magic)
  912.     reg_magic = MAGIC_ON;
  913.     else
  914.     reg_magic = MAGIC_OFF;
  915.     num_complex_braces = 0;
  916.     regnpar = 1;
  917.     vim_memset(had_endbrace, 0, sizeof(had_endbrace));
  918. #ifdef FEAT_SYN_HL
  919.     regnzpar = 1;
  920.     re_has_z = 0;
  921. #endif
  922.     regsize = 0L;
  923.     regflags = 0;
  924. #if defined(FEAT_SYN_HL) || defined(PROTO)
  925.     had_eol = FALSE;
  926. #endif
  927. }
  928.  
  929. #if defined(FEAT_SYN_HL) || defined(PROTO)
  930. /*
  931.  * Check if during the previous call to vim_regcomp the EOL item "$" has been
  932.  * found.  This is messy, but it works fine.
  933.  */
  934.     int
  935. vim_regcomp_had_eol()
  936. {
  937.     return had_eol;
  938. }
  939. #endif
  940.  
  941. /*
  942.  * reg - regular expression, i.e. main body or parenthesized thing
  943.  *
  944.  * Caller must absorb opening parenthesis.
  945.  *
  946.  * Combining parenthesis handling with the base level of regular expression
  947.  * is a trifle forced, but the need to tie the tails of the branches to what
  948.  * follows makes it hard to avoid.
  949.  */
  950.     static char_u *
  951. reg(paren, flagp)
  952.     int        paren;    /* REG_NOPAREN, REG_PAREN, REG_NPAREN or REG_ZPAREN */
  953.     int        *flagp;
  954. {
  955.     char_u    *ret;
  956.     char_u    *br;
  957.     char_u    *ender;
  958.     int        parno = 0;
  959.     int        flags;
  960.  
  961.     *flagp = HASWIDTH;        /* Tentatively. */
  962.  
  963. #ifdef FEAT_SYN_HL
  964.     if (paren == REG_ZPAREN)
  965.     {
  966.     /* Make a ZOPEN node. */
  967.     if (regnzpar >= NSUBEXP)
  968.         EMSG_RET_NULL("E50: Too many \\z(");
  969.     parno = regnzpar;
  970.     regnzpar++;
  971.     ret = regnode(ZOPEN + parno);
  972.     }
  973.     else
  974. #endif
  975.     if (paren == REG_PAREN)
  976.     {
  977.     /* Make a MOPEN node. */
  978.     if (regnpar >= NSUBEXP)
  979.         EMSG_M_RET_NULL("E51: Too many %s(", reg_magic == MAGIC_ALL);
  980.     parno = regnpar;
  981.     ++regnpar;
  982.     ret = regnode(MOPEN + parno);
  983.     }
  984.     else if (paren == REG_NPAREN)
  985.     {
  986.     /* Make a NOPEN node. */
  987.     ret = regnode(NOPEN);
  988.     }
  989.     else
  990.     ret = NULL;
  991.  
  992.     /* Pick up the branches, linking them together. */
  993.     br = regbranch(&flags);
  994.     if (br == NULL)
  995.     return NULL;
  996.     if (ret != NULL)
  997.     regtail(ret, br);    /* [MZ]OPEN -> first. */
  998.     else
  999.     ret = br;
  1000.     /* If one of the branches can be zero-width, the whole thing can.
  1001.      * If one of the branches has * at start or matches a line-break, the
  1002.      * whole thing can. */
  1003.     if (!(flags & HASWIDTH))
  1004.     *flagp &= ~HASWIDTH;
  1005.     *flagp |= flags & (SPSTART | HASNL);
  1006.     while (peekchr() == Magic('|'))
  1007.     {
  1008.     skipchr();
  1009.     br = regbranch(&flags);
  1010.     if (br == NULL)
  1011.         return NULL;
  1012.     regtail(ret, br);    /* BRANCH -> BRANCH. */
  1013.     if (!(flags & HASWIDTH))
  1014.         *flagp &= ~HASWIDTH;
  1015.     *flagp |= flags & (SPSTART | HASNL);
  1016.     }
  1017.  
  1018.     /* Make a closing node, and hook it on the end. */
  1019.     ender = regnode(
  1020. #ifdef FEAT_SYN_HL
  1021.         paren == REG_ZPAREN ? ZCLOSE + parno :
  1022. #endif
  1023.         paren == REG_PAREN ? MCLOSE + parno :
  1024.         paren == REG_NPAREN ? NCLOSE : END);
  1025.     regtail(ret, ender);
  1026.  
  1027.     /* Hook the tails of the branches to the closing node. */
  1028.     for (br = ret; br != NULL; br = regnext(br))
  1029.     regoptail(br, ender);
  1030.  
  1031.     /* Check for proper termination. */
  1032.     if (paren != REG_NOPAREN && getchr() != Magic(')'))
  1033.     {
  1034. #ifdef FEAT_SYN_HL
  1035.     if (paren == REG_ZPAREN)
  1036.         EMSG_RET_NULL("E52: Unmatched \\z(")
  1037.     else
  1038. #endif
  1039.         if (paren == REG_NPAREN)
  1040.         EMSG_M_RET_NULL("E53: Unmatched %s%%(", reg_magic == MAGIC_ALL)
  1041.     else
  1042.         EMSG_M_RET_NULL("E54: Unmatched %s(", reg_magic == MAGIC_ALL)
  1043.     }
  1044.     else if (paren == REG_NOPAREN && peekchr() != NUL)
  1045.     {
  1046.     if (curchr == Magic(')'))
  1047.         EMSG_M_RET_NULL("E55: Unmatched %s)", reg_magic == MAGIC_ALL)
  1048.     else
  1049.         EMSG_RET_NULL(e_trailing)    /* "Can't happen". */
  1050.     /* NOTREACHED */
  1051.     }
  1052.     /*
  1053.      * Here we set the flag allowing back references to this set of
  1054.      * parentheses.
  1055.      */
  1056.     if (paren == REG_PAREN)
  1057.     had_endbrace[parno] = TRUE;    /* have seen the close paren */
  1058.     return ret;
  1059. }
  1060.  
  1061. /*
  1062.  * regbranch - one alternative of an | operator
  1063.  *
  1064.  * Implements the & operator.
  1065.  */
  1066.     static char_u *
  1067. regbranch(flagp)
  1068.     int        *flagp;
  1069. {
  1070.     char_u    *ret;
  1071.     char_u    *chain = NULL;
  1072.     char_u    *latest;
  1073.     int        flags;
  1074.  
  1075.     *flagp = WORST | HASNL;        /* Tentatively. */
  1076.  
  1077.     ret = regnode(BRANCH);
  1078.     for (;;)
  1079.     {
  1080.     latest = regconcat(&flags);
  1081.     if (latest == NULL)
  1082.         return NULL;
  1083.     /* If one of the branches has width, the whole thing has.  If one of
  1084.      * the branches anchors at start-of-line, the whole thing does. */
  1085.     *flagp |= flags & (HASWIDTH | SPSTART);
  1086.     /* If one of the branches doesn't match a line-break, the whole thing
  1087.      * doesn't. */
  1088.     *flagp &= ~HASNL | (flags & HASNL);
  1089.     if (chain != NULL)
  1090.         regtail(chain, latest);
  1091.     if (peekchr() != Magic('&'))
  1092.         break;
  1093.     skipchr();
  1094.     regtail(latest, regnode(END)); /* operand ends */
  1095.     reginsert(MATCH, latest);
  1096.     chain = latest;
  1097.     }
  1098.  
  1099.     return ret;
  1100. }
  1101.  
  1102. /*
  1103.  * regbranch - one alternative of an | or & operator
  1104.  *
  1105.  * Implements the concatenation operator.
  1106.  */
  1107.     static char_u *
  1108. regconcat(flagp)
  1109.     int        *flagp;
  1110. {
  1111.     char_u    *first = NULL;
  1112.     char_u    *chain = NULL;
  1113.     char_u    *latest;
  1114.     int        flags;
  1115.     int        cont = TRUE;
  1116.  
  1117.     *flagp = WORST;        /* Tentatively. */
  1118.  
  1119.     while (cont)
  1120.     {
  1121.     switch (peekchr())
  1122.     {
  1123.         case NUL:
  1124.         case Magic('|'):
  1125.         case Magic('&'):
  1126.         case Magic(')'):
  1127.                 cont = FALSE;
  1128.                 break;
  1129.         case Magic('c'):
  1130.                 regflags |= RF_ICASE;
  1131.                 skipchr_keepstart();
  1132.                 break;
  1133.         case Magic('C'):
  1134.                 regflags |= RF_NOICASE;
  1135.                 skipchr_keepstart();
  1136.                 break;
  1137.         case Magic('v'):
  1138.                 reg_magic = MAGIC_ALL;
  1139.                 skipchr_keepstart();
  1140.                 curchr = -1;
  1141.                 break;
  1142.         case Magic('m'):
  1143.                 reg_magic = MAGIC_ON;
  1144.                 skipchr_keepstart();
  1145.                 curchr = -1;
  1146.                 break;
  1147.         case Magic('M'):
  1148.                 reg_magic = MAGIC_OFF;
  1149.                 skipchr_keepstart();
  1150.                 curchr = -1;
  1151.                 break;
  1152.         case Magic('V'):
  1153.                 reg_magic = MAGIC_NONE;
  1154.                 skipchr_keepstart();
  1155.                 curchr = -1;
  1156.                 break;
  1157.         default:
  1158.                 latest = regpiece(&flags);
  1159.                 if (latest == NULL)
  1160.                 return NULL;
  1161.                 *flagp |= flags & (HASWIDTH | HASNL);
  1162.                 if (chain == NULL)    /* First piece. */
  1163.                 *flagp |= flags & SPSTART;
  1164.                 else
  1165.                 regtail(chain, latest);
  1166.                 chain = latest;
  1167.                 if (first == NULL)
  1168.                 first = latest;
  1169.                 break;
  1170.     }
  1171.     }
  1172.     if (first == NULL)        /* Loop ran zero times. */
  1173.     first = regnode(NOTHING);
  1174.     return first;
  1175. }
  1176.  
  1177. /*
  1178.  * regpiece - something followed by possible [*+=]
  1179.  *
  1180.  * Note that the branching code sequences used for = and the general cases
  1181.  * of * and + are somewhat optimized:  they use the same NOTHING node as
  1182.  * both the endmarker for their branch list and the body of the last branch.
  1183.  * It might seem that this node could be dispensed with entirely, but the
  1184.  * endmarker role is not redundant.
  1185.  */
  1186.     static char_u *
  1187. regpiece(flagp)
  1188.     int            *flagp;
  1189. {
  1190.     char_u        *ret;
  1191.     int            op;
  1192.     char_u        *next;
  1193.     int            flags;
  1194.     long        minval;
  1195.     long        maxval;
  1196.  
  1197.     ret = regatom(&flags);
  1198.     if (ret == NULL)
  1199.     return NULL;
  1200.  
  1201.     op = peekchr();
  1202.     if (re_multi_type(op) == NOT_MULTI)
  1203.     {
  1204.     *flagp = flags;
  1205.     return ret;
  1206.     }
  1207.     if (!(flags & HASWIDTH) && re_multi_type(op) == MULTI_MULT)
  1208.     {
  1209.     if (op == Magic('*'))
  1210.         EMSG_M_RET_NULL("E56: %s* operand could be empty",
  1211.                                reg_magic >= MAGIC_ON);
  1212.     if (op == Magic('+'))
  1213.         EMSG_M_RET_NULL("E57: %s+ operand could be empty",
  1214.                                reg_magic == MAGIC_ALL);
  1215.     EMSG_M_RET_NULL("E58: %s{ operand could be empty",
  1216.                               reg_magic == MAGIC_ALL);
  1217.     }
  1218.     *flagp = (WORST | SPSTART | (flags & HASNL));    /* default flags */
  1219.  
  1220.     skipchr();
  1221.     switch (op)
  1222.     {
  1223.     case Magic('*'):
  1224.         if (flags & SIMPLE)
  1225.         reginsert(STAR, ret);
  1226.         else
  1227.         {
  1228.         /* Emit x* as (x&|), where & means "self". */
  1229.         reginsert(BRANCH, ret); /* Either x */
  1230.         regoptail(ret, regnode(BACK));    /* and loop */
  1231.         regoptail(ret, ret);    /* back */
  1232.         regtail(ret, regnode(BRANCH));    /* or */
  1233.         regtail(ret, regnode(NOTHING)); /* null. */
  1234.         }
  1235.         break;
  1236.  
  1237.     case Magic('+'):
  1238.         if (flags & SIMPLE)
  1239.         reginsert(PLUS, ret);
  1240.         else
  1241.         {
  1242.         /* Emit x+ as x(&|), where & means "self". */
  1243.         next = regnode(BRANCH); /* Either */
  1244.         regtail(ret, next);
  1245.         regtail(regnode(BACK), ret);    /* loop back */
  1246.         regtail(next, regnode(BRANCH)); /* or */
  1247.         regtail(ret, regnode(NOTHING)); /* null. */
  1248.         }
  1249.         *flagp = (WORST | HASWIDTH | (flags & HASNL));
  1250.         break;
  1251.  
  1252.     case Magic('@'):
  1253.         {
  1254.         int    lop = END;
  1255.  
  1256.         switch (no_Magic(getchr()))
  1257.         {
  1258.             case '=': lop = MATCH; break;          /* \@= */
  1259.             case '!': lop = NOMATCH; break;          /* \@! */
  1260.             case '>': lop = SUBPAT; break;          /* \@> */
  1261.             case '<': switch (no_Magic(getchr()))
  1262.                   {
  1263.                   case '=': lop = BEHIND; break;   /* \@<= */
  1264.                   case '!': lop = NOBEHIND; break; /* \@<! */
  1265.                   }
  1266.         }
  1267.         if (lop == END)
  1268.             EMSG_M_RET_NULL("E59: invalid character after %s@",
  1269.                               reg_magic == MAGIC_ALL);
  1270.         /* Look behind must match with behind_pos. */
  1271.         if (lop == BEHIND || lop == NOBEHIND)
  1272.             regtail(ret, regnode(BHPOS));
  1273.         regtail(ret, regnode(END)); /* operand ends */
  1274.         reginsert(lop, ret);
  1275.         break;
  1276.         }
  1277.  
  1278.     case Magic('?'):
  1279.     case Magic('='):
  1280.         /* Emit x= as (x|) */
  1281.         reginsert(BRANCH, ret); /* Either x */
  1282.         regtail(ret, regnode(BRANCH));    /* or */
  1283.         next = regnode(NOTHING);/* null. */
  1284.         regtail(ret, next);
  1285.         regoptail(ret, next);
  1286.         break;
  1287.  
  1288.     case Magic('{'):
  1289.         if (!read_limits(&minval, &maxval))
  1290.         return NULL;
  1291.         if (flags & SIMPLE)
  1292.         {
  1293.         reginsert(BRACE_SIMPLE, ret);
  1294.         reginsert_limits(BRACE_LIMITS, minval, maxval, ret);
  1295.         }
  1296.         else
  1297.         {
  1298.         if (num_complex_braces >= 10)
  1299.             EMSG_M_RET_NULL("E60: Too many complex %s{...}s",
  1300.                               reg_magic == MAGIC_ALL);
  1301.         reginsert(BRACE_COMPLEX + num_complex_braces, ret);
  1302.         regoptail(ret, regnode(BACK));
  1303.         regoptail(ret, ret);
  1304.         reginsert_limits(BRACE_LIMITS, minval, maxval, ret);
  1305.         ++num_complex_braces;
  1306.         }
  1307.         if (minval > 0)
  1308.         *flagp = (HASWIDTH | (flags & HASNL));
  1309.         break;
  1310.     }
  1311.     if (re_multi_type(peekchr()) != NOT_MULTI)
  1312.     {
  1313.     /* Can't have a multi follow a multi. */
  1314.     if (peekchr() == Magic('*'))
  1315.         sprintf((char *)IObuff, _("E61: Nested %s*"),
  1316.                         reg_magic >= MAGIC_ON ? "" : "\\");
  1317.     else
  1318.         sprintf((char *)IObuff, _("E62: Nested %s%c"),
  1319.         reg_magic == MAGIC_ALL ? "" : "\\", no_Magic(peekchr()));
  1320.     EMSG_RET_NULL(IObuff);
  1321.     }
  1322.  
  1323.     return ret;
  1324. }
  1325.  
  1326. /*
  1327.  * regatom - the lowest level
  1328.  *
  1329.  * Optimization:  gobbles an entire sequence of ordinary characters so that
  1330.  * it can turn them into a single node, which is smaller to store and
  1331.  * faster to run.  Don't do this when one_exactly is set.
  1332.  */
  1333.     static char_u *
  1334. regatom(flagp)
  1335.     int           *flagp;
  1336. {
  1337.     char_u        *ret;
  1338.     int            flags;
  1339.     int            cpo_lit;        /* 'cpoptions' contains 'l' flag */
  1340.     int            c;
  1341.     static char_u   *classchars = (char_u *)".iIkKfFpPsSdDxXoOwWhHaAlLuU";
  1342.     static int        classcodes[] = {ANY, IDENT, SIDENT, KWORD, SKWORD,
  1343.                     FNAME, SFNAME, PRINT, SPRINT,
  1344.                     WHITE, NWHITE, DIGIT, NDIGIT,
  1345.                     HEX, NHEX, OCTAL, NOCTAL,
  1346.                     WORD, NWORD, HEAD, NHEAD,
  1347.                     ALPHA, NALPHA, LOWER, NLOWER,
  1348.                     UPPER, NUPPER
  1349.                     };
  1350.     char_u        *p;
  1351.     int            extra = 0;
  1352.  
  1353.     *flagp = WORST;        /* Tentatively. */
  1354.     cpo_lit = (!reg_syn && vim_strchr(p_cpo, CPO_LITERAL) != NULL);
  1355.  
  1356.     c = getchr();
  1357.     switch (c)
  1358.     {
  1359.       case Magic('^'):
  1360.     ret = regnode(BOL);
  1361.     break;
  1362.  
  1363.       case Magic('$'):
  1364.     ret = regnode(EOL);
  1365. #if defined(FEAT_SYN_HL) || defined(PROTO)
  1366.     had_eol = TRUE;
  1367. #endif
  1368.     break;
  1369.  
  1370.       case Magic('<'):
  1371.     ret = regnode(BOW);
  1372.     break;
  1373.  
  1374.       case Magic('>'):
  1375.     ret = regnode(EOW);
  1376.     break;
  1377.  
  1378.       case Magic('_'):
  1379.     c = no_Magic(getchr());
  1380.     if (c == '^')        /* "\_^" is start-of-line */
  1381.     {
  1382.         ret = regnode(BOL);
  1383.         break;
  1384.     }
  1385.     if (c == '$')        /* "\_$" is end-of-line */
  1386.     {
  1387.         ret = regnode(EOL);
  1388. #if defined(FEAT_SYN_HL) || defined(PROTO)
  1389.         had_eol = TRUE;
  1390. #endif
  1391.         break;
  1392.     }
  1393.  
  1394.     extra = ADD_NL;
  1395.     *flagp |= HASNL;
  1396.  
  1397.     /* "\_[" is character range plus newline */
  1398.     if (c == '[')
  1399.         goto collection;
  1400.  
  1401.     /* "\_x" is character class plus newline */
  1402.     /*FALLTHROUGH*/
  1403.  
  1404.     /*
  1405.      * Character classes.
  1406.      */
  1407.       case Magic('.'):
  1408.       case Magic('i'):
  1409.       case Magic('I'):
  1410.       case Magic('k'):
  1411.       case Magic('K'):
  1412.       case Magic('f'):
  1413.       case Magic('F'):
  1414.       case Magic('p'):
  1415.       case Magic('P'):
  1416.       case Magic('s'):
  1417.       case Magic('S'):
  1418.       case Magic('d'):
  1419.       case Magic('D'):
  1420.       case Magic('x'):
  1421.       case Magic('X'):
  1422.       case Magic('o'):
  1423.       case Magic('O'):
  1424.       case Magic('w'):
  1425.       case Magic('W'):
  1426.       case Magic('h'):
  1427.       case Magic('H'):
  1428.       case Magic('a'):
  1429.       case Magic('A'):
  1430.       case Magic('l'):
  1431.       case Magic('L'):
  1432.       case Magic('u'):
  1433.       case Magic('U'):
  1434.     p = vim_strchr(classchars, no_Magic(c));
  1435.     if (p == NULL)
  1436.         EMSG_RET_NULL("E63: invalid use of \\_");
  1437.     ret = regnode(classcodes[p - classchars] + extra);
  1438.     *flagp |= HASWIDTH | SIMPLE;
  1439.     break;
  1440.  
  1441.       case Magic('n'):
  1442.     ret = regnode(NEWL);
  1443.     *flagp |= HASWIDTH | HASNL;
  1444.     break;
  1445.  
  1446.       case Magic('('):
  1447.     ret = reg(REG_PAREN, &flags);
  1448.     if (ret == NULL)
  1449.         return NULL;
  1450.     *flagp |= flags & (HASWIDTH | SPSTART | HASNL);
  1451.     break;
  1452.  
  1453.       case NUL:
  1454.       case Magic('|'):
  1455.       case Magic('&'):
  1456.       case Magic(')'):
  1457.     EMSG_RET_NULL(e_internal);        /* Supposed to be caught earlier. */
  1458.     /* NOTREACHED */
  1459.  
  1460.       case Magic('='):
  1461.       case Magic('?'):
  1462.       case Magic('+'):
  1463.       case Magic('@'):
  1464.       case Magic('{'):
  1465.       case Magic('*'):
  1466.     c = no_Magic(c);
  1467.     sprintf((char *)IObuff, _("E64: %s%c follows nothing"),
  1468.         (c == '*' ? reg_magic >= MAGIC_ON : reg_magic == MAGIC_ALL)
  1469.         ? "" : "\\", c);
  1470.     EMSG_RET_NULL(IObuff);
  1471.     /* NOTREACHED */
  1472.  
  1473.       case Magic('~'):        /* previous substitute pattern */
  1474.         if (reg_prev_sub)
  1475.         {
  1476.         char_u        *lp;
  1477.  
  1478.         ret = regnode(EXACTLY);
  1479.         lp = reg_prev_sub;
  1480.         while (*lp != NUL)
  1481.             regc(*lp++);
  1482.         regc(NUL);
  1483.         if (*reg_prev_sub != NUL)
  1484.         {
  1485.             *flagp |= HASWIDTH;
  1486.             if ((lp - reg_prev_sub) == 1)
  1487.             *flagp |= SIMPLE;
  1488.         }
  1489.         }
  1490.         else
  1491.         EMSG_RET_NULL(e_nopresub);
  1492.         break;
  1493.  
  1494.       case Magic('1'):
  1495.       case Magic('2'):
  1496.       case Magic('3'):
  1497.       case Magic('4'):
  1498.       case Magic('5'):
  1499.       case Magic('6'):
  1500.       case Magic('7'):
  1501.       case Magic('8'):
  1502.       case Magic('9'):
  1503.         {
  1504.         int            refnum;
  1505.  
  1506.         refnum = c - Magic('0');
  1507.         /*
  1508.          * Check if the back reference is legal. We must have seen the
  1509.          * close brace.
  1510.          * TODO: Should also check that we don't refer to something
  1511.          * that is repeated (+*=): what instance of the repetition
  1512.          * should we match?
  1513.          */
  1514.         if (had_endbrace[refnum])
  1515.             ret = regnode(BACKREF + refnum);
  1516.         else
  1517.             EMSG_RET_NULL("E65: Illegal back reference");
  1518.         }
  1519.         break;
  1520.  
  1521. #ifdef FEAT_SYN_HL
  1522.       case Magic('z'):
  1523.     {
  1524.         c = no_Magic(getchr());
  1525.         switch (c)
  1526.         {
  1527.         case '(': if (reg_do_extmatch != REX_SET)
  1528.                   EMSG_RET_NULL("E66: \\z( not allowed here");
  1529.               ret = reg(REG_ZPAREN, &flags);
  1530.               if (ret == NULL)
  1531.                   return NULL;
  1532.               *flagp |= flags & (HASWIDTH | SPSTART | HASNL);
  1533.               re_has_z = REX_SET;
  1534.               break;
  1535.  
  1536.         case '1':
  1537.         case '2':
  1538.         case '3':
  1539.         case '4':
  1540.         case '5':
  1541.         case '6':
  1542.         case '7':
  1543.         case '8':
  1544.         case '9': if (reg_do_extmatch != REX_USE)
  1545.                   EMSG_RET_NULL("E67: \\z1 et al. not allowed here");
  1546.               ret = regnode(ZREF + c - '0');
  1547.               re_has_z = REX_USE;
  1548.               break;
  1549.  
  1550.         case 's': ret = regnode(MOPEN + 0);
  1551.               break;
  1552.  
  1553.         case 'e': ret = regnode(MCLOSE + 0);
  1554.               break;
  1555.  
  1556.         default:  EMSG_RET_NULL("E68: Invalid character after \\z");
  1557.         }
  1558.     }
  1559.     break;
  1560.  
  1561.       case Magic('%'):
  1562.     {
  1563.         c = no_Magic(getchr());
  1564.         switch (c)
  1565.         {
  1566.         /* () without a back reference */
  1567.         case '(':
  1568.             ret = reg(REG_NPAREN, &flags);
  1569.             if (ret == NULL)
  1570.             return NULL;
  1571.             *flagp |= flags & (HASWIDTH | SPSTART | HASNL);
  1572.             break;
  1573.  
  1574.         /* Catch \%^ and \%$ regardless of where they appear in the
  1575.          * pattern -- regardless of whether or not it makes sense. */
  1576.         case '^':
  1577.             ret = regnode(RE_BOF);
  1578.             break;
  1579.  
  1580.         case '$':
  1581.             ret = regnode(RE_EOF);
  1582.             break;
  1583.  
  1584.         case '#':
  1585.             ret = regnode(CURSOR);
  1586.             break;
  1587.  
  1588.         /* \%[abc]: Emit as a list of branches, all ending at the last
  1589.          * branch which matches nothing. */
  1590.         case '[':
  1591.               {
  1592.                   char_u    *lastbranch;
  1593.                   char_u    *lastnode = NULL;
  1594.                   char_u    *br;
  1595.  
  1596.                   ret = NULL;
  1597.                   while ((c = getchr()) != ']')
  1598.                   {
  1599.                   if (c == NUL)
  1600.                       EMSG_M_RET_NULL("E69: Missing ] after %s%%[",
  1601.                               reg_magic == MAGIC_ALL);
  1602.                   br = regnode(BRANCH);
  1603.                   if (ret == NULL)
  1604.                       ret = br;
  1605.                   else
  1606.                       regtail(lastnode, br);
  1607.  
  1608.                   ungetchr();
  1609.                   one_exactly = TRUE;
  1610.                   lastnode = regatom(flagp);
  1611.                   one_exactly = FALSE;
  1612.                   if (lastnode == NULL)
  1613.                       return NULL;
  1614.                   }
  1615.                   if (ret == NULL)
  1616.                   EMSG_M_RET_NULL("E70: Empty %s%%[]",
  1617.                               reg_magic == MAGIC_ALL);
  1618.                   lastbranch = regnode(BRANCH);
  1619.                   br = regnode(NOTHING);
  1620.                   if (ret != JUST_CALC_SIZE)
  1621.                   {
  1622.                   regtail(lastnode, br);
  1623.                   regtail(lastbranch, br);
  1624.                   /* connect all branches to the NOTHING
  1625.                    * branch at the end */
  1626.                   for (br = ret; br != lastnode; )
  1627.                   {
  1628.                       if (OP(br) == BRANCH)
  1629.                       {
  1630.                       regtail(br, lastbranch);
  1631.                       br = OPERAND(br);
  1632.                       }
  1633.                       else
  1634.                       br = regnext(br);
  1635.                   }
  1636.                   }
  1637.                   *flagp &= ~HASWIDTH;
  1638.                   break;
  1639.               }
  1640.  
  1641.         default:
  1642.               if (isdigit(c) || c == '<' || c == '>')
  1643.               {
  1644.                   long_u    n = 0;
  1645.                   int    cmp;
  1646.  
  1647.                   cmp = c;
  1648.                   if (cmp == '<' || cmp == '>')
  1649.                   c = getchr();
  1650.                   while (isdigit(c))
  1651.                   {
  1652.                   n = n * 10 + (c - '0');
  1653.                   c = getchr();
  1654.                   }
  1655.                   if (c == 'l' || c == 'c' || c == 'v')
  1656.                   {
  1657.                   if (c == 'l')
  1658.                       ret = regnode(RE_LNUM);
  1659.                   else if (c == 'c')
  1660.                       ret = regnode(RE_COL);
  1661.                   else
  1662.                       ret = regnode(RE_VCOL);
  1663.                   if (ret == JUST_CALC_SIZE)
  1664.                       regsize += 5;
  1665.                   else
  1666.                   {
  1667.                       /* put the number and the optional
  1668.                        * comparator after the opcode */
  1669.                       regcode = re_put_long(regcode, n);
  1670.                       *regcode++ = cmp;
  1671.                   }
  1672.                   break;
  1673.                   }
  1674.               }
  1675.  
  1676.               EMSG_M_RET_NULL("E71: Invalid character after %s%%",
  1677.                               reg_magic == MAGIC_ALL);
  1678.         }
  1679.     }
  1680.     break;
  1681. #endif
  1682.  
  1683.       case Magic('['):
  1684. collection:
  1685.     {
  1686.         char_u    *lp;
  1687.  
  1688.         /*
  1689.          * If there is no matching ']', we assume the '[' is a normal
  1690.          * character.  This makes 'incsearch' and ":help [" work.
  1691.          */
  1692.         lp = skip_anyof(regparse);
  1693.         if (*lp == ']')    /* there is a matching ']' */
  1694.         {
  1695.         int    startc = -1;    /* > 0 when next '-' is a range */
  1696.         int    endc;
  1697.  
  1698.         /*
  1699.          * In a character class, different parsing rules apply.
  1700.          * Not even \ is special anymore, nothing is.
  1701.          */
  1702.         if (*regparse == '^')        /* Complement of range. */
  1703.         {
  1704.             ret = regnode(ANYBUT + extra);
  1705.             regparse++;
  1706.         }
  1707.         else
  1708.             ret = regnode(ANYOF + extra);
  1709.  
  1710.         /* At the start ']' and '-' mean the literal character. */
  1711.         if (*regparse == ']' || *regparse == '-')
  1712.             regc(*regparse++);
  1713.  
  1714.         while (*regparse != NUL && *regparse != ']')
  1715.         {
  1716.             if (*regparse == '-')
  1717.             {
  1718.             ++regparse;
  1719.             /* The '-' is not used for a range at the end and
  1720.              * after or before a '\n'. */
  1721.             if (*regparse == ']' || *regparse == NUL
  1722.                 || startc == -1
  1723.                 || (regparse[0] == '\\' && regparse[1] == 'n'))
  1724.             {
  1725.                 regc('-');
  1726.                 startc = '-';    /* [--x] is a range */
  1727.             }
  1728.             else
  1729.             {
  1730. #ifdef FEAT_MBYTE
  1731.                 if (has_mbyte)
  1732.                 endc = mb_ptr2char_adv(®parse);
  1733.                 else
  1734. #endif
  1735.                 endc = *regparse++;
  1736.                 if (startc > endc)
  1737.                 EMSG_RET_NULL(e_invrange);
  1738. #ifdef FEAT_MBYTE
  1739.                 if (has_mbyte && ((*mb_char2len)(startc) > 1
  1740.                          || (*mb_char2len)(endc) > 1))
  1741.                 {
  1742.                 /* Limit to a range of 256 chars */
  1743.                 if (endc > startc + 256)
  1744.                     EMSG_RET_NULL(e_invrange);
  1745.                 while (++startc <= endc)
  1746.                     regmbc(startc);
  1747.                 }
  1748.                 else
  1749. #endif
  1750.                 {
  1751. #ifdef EBCDIC
  1752.                 int    alpha_only = FALSE;
  1753.  
  1754.                 /* for alphabetical range skip the gaps
  1755.                  * 'i'-'j', 'r'-'s', 'I'-'J' and 'R'-'S'.  */
  1756.                 if (isalpha(startc) && isalpha(endc))
  1757.                     alpha_only = TRUE;
  1758. #endif
  1759.                 while (++startc <= endc)
  1760. #ifdef EBCDIC
  1761.                     if (!alpha_only || isalpha(startc))
  1762. #endif
  1763.                     regc(startc);
  1764.                 }
  1765.                 startc = -1;
  1766.             }
  1767.             }
  1768.             /*
  1769.              * Only "\]", "\^", "\]" and "\\" are special in Vi.  Vim
  1770.              * accepts "\t", "\e", etc., but only when the 'l' flag in
  1771.              * 'cpoptions' is not included.
  1772.              */
  1773.             else if (*regparse == '\\'
  1774.                 && (vim_strchr(REGEXP_INRANGE, regparse[1]) != NULL
  1775.                 || (!cpo_lit
  1776.                     && vim_strchr(REGEXP_ABBR,
  1777.                                regparse[1]) != NULL)))
  1778.             {
  1779.             regparse++;
  1780.             if (*regparse == 'n')
  1781.             {
  1782.                 /* '\n' in range: also match NL */
  1783.                 if (ret != JUST_CALC_SIZE)
  1784.                 {
  1785.                 if (*ret == ANYBUT)
  1786.                     *ret = ANYBUT + ADD_NL;
  1787.                 else if (*ret == ANYOF)
  1788.                     *ret = ANYOF + ADD_NL;
  1789.                 /* else: must have had a \n already */
  1790.                 }
  1791.                 *flagp |= HASNL;
  1792.                 regparse++;
  1793.                 startc = -1;
  1794.             }
  1795.             else
  1796.             {
  1797.                 startc = backslash_trans(*regparse++);
  1798.                 regc(startc);
  1799.             }
  1800.             }
  1801.             else if (*regparse == '[')
  1802.             {
  1803.             int c_class;
  1804.             int cu;
  1805.  
  1806.             c_class = skip_class_name(®parse);
  1807.             startc = -1;
  1808.             /* Characters assumed to be 8 bits! */
  1809.             switch (c_class)
  1810.             {
  1811.                 case CLASS_NONE:
  1812.                 /* literal '[', allow [[-x] as a range */
  1813.                 startc = *regparse++;
  1814.                 regc(startc);
  1815.                 break;
  1816.                 case CLASS_ALNUM:
  1817.                 for (cu = 1; cu <= 255; cu++)
  1818.                     if (isalnum(cu))
  1819.                     regc(cu);
  1820.                 break;
  1821.                 case CLASS_ALPHA:
  1822.                 for (cu = 1; cu <= 255; cu++)
  1823.                     if (isalpha(cu))
  1824.                     regc(cu);
  1825.                 break;
  1826.                 case CLASS_BLANK:
  1827.                 regc(' ');
  1828.                 regc('\t');
  1829.                 break;
  1830.                 case CLASS_CNTRL:
  1831.                 for (cu = 1; cu <= 255; cu++)
  1832.                     if (iscntrl(cu))
  1833.                     regc(cu);
  1834.                 break;
  1835.                 case CLASS_DIGIT:
  1836.                 for (cu = 1; cu <= 255; cu++)
  1837.                     if (isdigit(cu))
  1838.                     regc(cu);
  1839.                 break;
  1840.                 case CLASS_GRAPH:
  1841.                 for (cu = 1; cu <= 255; cu++)
  1842.                     if (isgraph(cu))
  1843.                     regc(cu);
  1844.                 break;
  1845.                 case CLASS_LOWER:
  1846.                 for (cu = 1; cu <= 255; cu++)
  1847.                     if (islower(cu))
  1848.                     regc(cu);
  1849.                 break;
  1850.                 case CLASS_PRINT:
  1851.                 for (cu = 1; cu <= 255; cu++)
  1852.                     if (vim_isprintc(cu))
  1853.                     regc(cu);
  1854.                 break;
  1855.                 case CLASS_PUNCT:
  1856.                 for (cu = 1; cu <= 255; cu++)
  1857.                     if (ispunct(cu))
  1858.                     regc(cu);
  1859.                 break;
  1860.                 case CLASS_SPACE:
  1861.                 for (cu = 9; cu <= 13; cu++)
  1862.                     regc(cu);
  1863.                 regc(' ');
  1864.                 break;
  1865.                 case CLASS_UPPER:
  1866.                 for (cu = 1; cu <= 255; cu++)
  1867.                     if (isupper(cu))
  1868.                     regc(cu);
  1869.                 break;
  1870.                 case CLASS_XDIGIT:
  1871.                 for (cu = 1; cu <= 255; cu++)
  1872.                     if (isxdigit(cu))
  1873.                     regc(cu);
  1874.                 break;
  1875.                 case CLASS_TAB:
  1876.                 regc('\t');
  1877.                 break;
  1878.                 case CLASS_RETURN:
  1879.                 regc('\r');
  1880.                 break;
  1881.                 case CLASS_BACKSPACE:
  1882.                 regc('\b');
  1883.                 break;
  1884.                 case CLASS_ESCAPE:
  1885.                 regc('\033');
  1886.                 break;
  1887.             }
  1888.             }
  1889.             else
  1890.             {
  1891. #ifdef FEAT_MBYTE
  1892.             if (has_mbyte)
  1893.             {
  1894.                 int    len;
  1895.  
  1896.                 /* produce a multibyte character, including any
  1897.                  * following composing characters */
  1898.                 startc = mb_ptr2char(regparse);
  1899.                 len = (*mb_ptr2len_check)(regparse);
  1900.                 if (enc_utf8 && utf_char2len(startc) != len)
  1901.                 startc = -1;    /* composing chars */
  1902.                 while (--len >= 0)
  1903.                 regc(*regparse++);
  1904.             }
  1905.             else
  1906. #endif
  1907.             {
  1908.                 startc = *regparse++;
  1909.                 regc(startc);
  1910.             }
  1911.             }
  1912.         }
  1913.         regc(NUL);
  1914.         prevchr_len = 1;    /* last char was the ']' */
  1915.         if (*regparse != ']')
  1916.             EMSG_RET_NULL(e_toomsbra);    /* Cannot happen? */
  1917.         skipchr();        /* let's be friends with the lexer again */
  1918.         *flagp |= HASWIDTH | SIMPLE;
  1919.         break;
  1920.         }
  1921.     }
  1922.     /* FALLTHROUGH */
  1923.  
  1924.       default:
  1925.     {
  1926.         int        len;
  1927.  
  1928. #ifdef FEAT_MBYTE
  1929.         /* A multi-byte character is handled as a separate atom if it's
  1930.          * before a multi. */
  1931.         if (has_mbyte && (*mb_char2len)(c) > 1
  1932.                      && re_multi_type(peekchr()) != NOT_MULTI)
  1933.         {
  1934.         ret = regnode(MULTIBYTECODE);
  1935.         regmbc(c);
  1936.         *flagp |= HASWIDTH | SIMPLE;
  1937.         break;
  1938.         }
  1939. #endif
  1940.  
  1941.         ret = regnode(EXACTLY);
  1942.  
  1943.         /*
  1944.          * Append characters as long as:
  1945.          * - there is no following multi, we then need the character in
  1946.          *   front of it as a single character operand
  1947.          * - not running into a Magic character
  1948.          * - "one_exactly" is not set
  1949.          * But always emit at least one character.  Might be a Multi,
  1950.          * e.g., a "[" without matching "]".
  1951.          */
  1952.         for (len = 0; c != NUL && (len == 0
  1953.             || (re_multi_type(peekchr()) == NOT_MULTI
  1954.                 && !one_exactly
  1955.                 && !is_Magic(c))); ++len)
  1956.         {
  1957.         c = no_Magic(c);
  1958. #ifdef FEAT_MBYTE
  1959.         if (has_mbyte)
  1960.         {
  1961.             regmbc(c);
  1962.             if (enc_utf8)
  1963.             {
  1964.             int    off;
  1965.  
  1966.             /* Need to get composing character too, directly
  1967.              * access regparse for that, because skipchr() skips
  1968.              * over composing chars. */
  1969.             ungetchr();
  1970.             if (*regparse == '\\' && regparse[1] != NUL)
  1971.                 off = 1;
  1972.             else
  1973.                 off = 0;
  1974.             for (;;)
  1975.             {
  1976.                 off += utf_ptr2len_check(regparse + off);
  1977.                 c = utf_ptr2char(regparse + off);
  1978.                 if (!utf_iscomposing(c))
  1979.                 break;
  1980.                 regmbc(c);
  1981.             }
  1982.             skipchr();
  1983.             }
  1984.         }
  1985.         else
  1986. #endif
  1987.             regc(c);
  1988.         c = getchr();
  1989.         }
  1990.         ungetchr();
  1991.  
  1992.         regc(NUL);
  1993.         *flagp |= HASWIDTH;
  1994.         if (len == 1)
  1995.         *flagp |= SIMPLE;
  1996.     }
  1997.     break;
  1998.     }
  1999.  
  2000.     return ret;
  2001. }
  2002.  
  2003. /*
  2004.  * emit a node
  2005.  * Return pointer to generated code.
  2006.  */
  2007.     static char_u *
  2008. regnode(op)
  2009.     int        op;
  2010. {
  2011.     char_u  *ret;
  2012.  
  2013.     ret = regcode;
  2014.     if (ret == JUST_CALC_SIZE)
  2015.     regsize += 3;
  2016.     else
  2017.     {
  2018.     *regcode++ = op;
  2019.     *regcode++ = NUL;        /* Null "next" pointer. */
  2020.     *regcode++ = NUL;
  2021.     }
  2022.     return ret;
  2023. }
  2024.  
  2025. /*
  2026.  * Emit (if appropriate) a byte of code
  2027.  */
  2028.     static void
  2029. regc(b)
  2030.     int        b;
  2031. {
  2032.     if (regcode == JUST_CALC_SIZE)
  2033.     regsize++;
  2034.     else
  2035.     *regcode++ = b;
  2036. }
  2037.  
  2038. #ifdef FEAT_MBYTE
  2039. /*
  2040.  * Emit (if appropriate) a multi-byte character of code
  2041.  */
  2042.     static void
  2043. regmbc(c)
  2044.     int        c;
  2045. {
  2046.     if (regcode == JUST_CALC_SIZE)
  2047.     regsize += (*mb_char2len)(c);
  2048.     else
  2049.     regcode += (*mb_char2bytes)(c, regcode);
  2050. }
  2051. #endif
  2052.  
  2053. /*
  2054.  * reginsert - insert an operator in front of already-emitted operand
  2055.  *
  2056.  * Means relocating the operand.
  2057.  */
  2058.     static void
  2059. reginsert(op, opnd)
  2060.     int        op;
  2061.     char_u     *opnd;
  2062. {
  2063.     char_u    *src;
  2064.     char_u    *dst;
  2065.     char_u    *place;
  2066.  
  2067.     if (regcode == JUST_CALC_SIZE)
  2068.     {
  2069.     regsize += 3;
  2070.     return;
  2071.     }
  2072.     src = regcode;
  2073.     regcode += 3;
  2074.     dst = regcode;
  2075.     while (src > opnd)
  2076.     *--dst = *--src;
  2077.  
  2078.     place = opnd;        /* Op node, where operand used to be. */
  2079.     *place++ = op;
  2080.     *place++ = NUL;
  2081.     *place = NUL;
  2082. }
  2083.  
  2084. /*
  2085.  * reginsert_limits - insert an operator in front of already-emitted operand.
  2086.  * The operator has the given limit values as operands.  Also set next pointer.
  2087.  *
  2088.  * Means relocating the operand.
  2089.  */
  2090.     static void
  2091. reginsert_limits(op, minval, maxval, opnd)
  2092.     int        op;
  2093.     long    minval;
  2094.     long    maxval;
  2095.     char_u    *opnd;
  2096. {
  2097.     char_u    *src;
  2098.     char_u    *dst;
  2099.     char_u    *place;
  2100.  
  2101.     if (regcode == JUST_CALC_SIZE)
  2102.     {
  2103.     regsize += 11;
  2104.     return;
  2105.     }
  2106.     src = regcode;
  2107.     regcode += 11;
  2108.     dst = regcode;
  2109.     while (src > opnd)
  2110.     *--dst = *--src;
  2111.  
  2112.     place = opnd;        /* Op node, where operand used to be. */
  2113.     *place++ = op;
  2114.     *place++ = NUL;
  2115.     *place++ = NUL;
  2116.     place = re_put_long(place, (long_u)minval);
  2117.     place = re_put_long(place, (long_u)maxval);
  2118.     regtail(opnd, place);
  2119. }
  2120.  
  2121. /*
  2122.  * Write a long as four bytes at "p" and return pointer to the next char.
  2123.  */
  2124.     static char_u *
  2125. re_put_long(p, val)
  2126.     char_u    *p;
  2127.     long_u    val;
  2128. {
  2129.     *p++ = (char_u) ((val >> 24) & 0377);
  2130.     *p++ = (char_u) ((val >> 16) & 0377);
  2131.     *p++ = (char_u) ((val >> 8) & 0377);
  2132.     *p++ = (char_u) (val & 0377);
  2133.     return p;
  2134. }
  2135.  
  2136. /*
  2137.  * regtail - set the next-pointer at the end of a node chain
  2138.  */
  2139.     static void
  2140. regtail(p, val)
  2141.     char_u    *p;
  2142.     char_u    *val;
  2143. {
  2144.     char_u    *scan;
  2145.     char_u    *temp;
  2146.     int        offset;
  2147.  
  2148.     if (p == JUST_CALC_SIZE)
  2149.     return;
  2150.  
  2151.     /* Find last node. */
  2152.     scan = p;
  2153.     for (;;)
  2154.     {
  2155.     temp = regnext(scan);
  2156.     if (temp == NULL)
  2157.         break;
  2158.     scan = temp;
  2159.     }
  2160.  
  2161.     if (OP(scan) == BACK)
  2162.     offset = (int)(scan - val);
  2163.     else
  2164.     offset = (int)(val - scan);
  2165.     *(scan + 1) = (char_u) (((unsigned)offset >> 8) & 0377);
  2166.     *(scan + 2) = (char_u) (offset & 0377);
  2167. }
  2168.  
  2169. /*
  2170.  * regoptail - regtail on item after a BRANCH; nop if none
  2171.  */
  2172.     static void
  2173. regoptail(p, val)
  2174.     char_u    *p;
  2175.     char_u    *val;
  2176. {
  2177.     /* When op is neither BRANCH nor BRACE_COMPLEX0-9, it is "operandless" */
  2178.     if (p == NULL || p == JUST_CALC_SIZE
  2179.         || (OP(p) != BRANCH
  2180.         && (OP(p) < BRACE_COMPLEX || OP(p) > BRACE_COMPLEX + 9)))
  2181.     return;
  2182.     regtail(OPERAND(p), val);
  2183. }
  2184.  
  2185. /*
  2186.  * getchr() - get the next character from the pattern. We know about
  2187.  * magic and such, so therefore we need a lexical analyzer.
  2188.  */
  2189.  
  2190. /* static int        curchr; */
  2191. static int    prevprevchr;
  2192. static int    prevchr;
  2193. static int    nextchr;    /* used for ungetchr() */
  2194. /*
  2195.  * Note: prevchr is sometimes -1 when we are not at the start,
  2196.  * eg in /[ ^I]^ the pattern was never found even if it existed, because ^ was
  2197.  * taken to be magic -- webb
  2198.  */
  2199. static int    at_start;    /* True when on the first character */
  2200. static int    prev_at_start;  /* True when on the second character */
  2201.  
  2202.     static void
  2203. initchr(str)
  2204.     char_u *str;
  2205. {
  2206.     regparse = str;
  2207.     prevchr_len = 0;
  2208.     curchr = prevprevchr = prevchr = nextchr = -1;
  2209.     at_start = TRUE;
  2210.     prev_at_start = FALSE;
  2211. }
  2212.  
  2213.     static int
  2214. peekchr()
  2215. {
  2216.     if (curchr == -1)
  2217.     {
  2218.     switch (curchr = regparse[0])
  2219.     {
  2220.     case '.':
  2221.     case '[':
  2222.     case '~':
  2223.         /* magic when 'magic' is on */
  2224.         if (reg_magic >= MAGIC_ON)
  2225.         curchr = Magic(curchr);
  2226.         break;
  2227.     case '(':
  2228.     case ')':
  2229.     case '{':
  2230.     case '%':
  2231.     case '+':
  2232.     case '=':
  2233.     case '?':
  2234.     case '@':
  2235.     case '!':
  2236.     case '&':
  2237.     case '|':
  2238.     case '<':
  2239.     case '>':
  2240.     case '#':    /* future ext. */
  2241.     case '"':    /* future ext. */
  2242.     case '\'':    /* future ext. */
  2243.     case ',':    /* future ext. */
  2244.     case '-':    /* future ext. */
  2245.     case ':':    /* future ext. */
  2246.     case ';':    /* future ext. */
  2247.     case '`':    /* future ext. */
  2248.     case '/':    /* Can't be used in / command */
  2249.         /* magic only after "\v" */
  2250.         if (reg_magic == MAGIC_ALL)
  2251.         curchr = Magic(curchr);
  2252.         break;
  2253.     case '*':
  2254.         /* * is not magic as the very first character, eg "?*ptr" and when
  2255.          * after '^', eg "/^*ptr" */
  2256.         if (reg_magic >= MAGIC_ON && !at_start
  2257.                  && !(prev_at_start && prevchr == Magic('^')))
  2258.         curchr = Magic('*');
  2259.         break;
  2260.     case '^':
  2261.         /* '^' is only magic as the very first character and if it's after
  2262.          * "\(", "\|", "\&' or "\n" */
  2263.         if (reg_magic >= MAGIC_OFF
  2264.             && (at_start
  2265.             || prevchr == Magic('(')
  2266.             || prevchr == Magic('|')
  2267.             || prevchr == Magic('&')
  2268.             || prevchr == Magic('n')
  2269.             || (no_Magic(prevchr) == '('
  2270.                 && prevprevchr == Magic('%'))))
  2271.         {
  2272.         curchr = Magic('^');
  2273.         at_start = TRUE;
  2274.         prev_at_start = FALSE;
  2275.         }
  2276.         break;
  2277.     case '$':
  2278.         /* '$' is only magic as the very last char and if it's in front of
  2279.          * either "\|", "\)", "\&", or "\n" */
  2280.         if (reg_magic >= MAGIC_OFF)
  2281.         {
  2282.         char_u *p = regparse + 1;
  2283.  
  2284.         /* ignore \c \C \m and \M after '$' */
  2285.         while (p[0] == '\\' && (p[1] == 'c' || p[1] == 'C'
  2286.                            || p[1] == 'm' || p[1] == 'M'))
  2287.             p += 2;
  2288.         if (p[0] == NUL
  2289.             || (p[0] == '\\'
  2290.                 && (p[1] == '|' || p[1] == '&' || p[1] == ')'
  2291.                 || p[1] == 'n')))
  2292.             curchr = Magic('$');
  2293.         }
  2294.         break;
  2295.     case '\\':
  2296.         {
  2297.         int c = regparse[1];
  2298.  
  2299.         if (c == NUL)
  2300.             curchr = '\\';    /* trailing '\' */
  2301. #ifdef EBCDIC
  2302.         else if (vim_strchr(META, c))
  2303. #else
  2304.         else if (c <= '~' && META_flags[c])
  2305. #endif
  2306.         {
  2307.             /*
  2308.              * META contains everything that may be magic sometimes,
  2309.              * except ^ and $ ("\^" and "\$" are only magic after
  2310.              * "\v").  We now fetch the next character and toggle its
  2311.              * magicness.  Therefore, \ is so meta-magic that it is
  2312.              * not in META.
  2313.              */
  2314.             curchr = -1;
  2315.             prev_at_start = at_start;
  2316.             at_start = FALSE;    /* be able to say "/\*ptr" */
  2317.             ++regparse;
  2318.             peekchr();
  2319.             --regparse;
  2320.             curchr = toggle_Magic(curchr);
  2321.         }
  2322.         else if (vim_strchr(REGEXP_ABBR, c))
  2323.         {
  2324.             /*
  2325.              * Handle abbreviations, like "\t" for TAB -- webb
  2326.              */
  2327.             curchr = backslash_trans(c);
  2328.         }
  2329.         else if (reg_magic == MAGIC_NONE && (c == '$' || c == '^'))
  2330.             curchr = toggle_Magic(c);
  2331.         else
  2332.         {
  2333.             /*
  2334.              * Next character can never be (made) magic?
  2335.              * Then backslashing it won't do anything.
  2336.              */
  2337. #ifdef FEAT_MBYTE
  2338.             if (has_mbyte)
  2339.             curchr = (*mb_ptr2char)(regparse + 1);
  2340.             else
  2341. #endif
  2342.             curchr = c;
  2343.         }
  2344.         break;
  2345.         }
  2346.  
  2347. #ifdef FEAT_MBYTE
  2348.     default:
  2349.         if (has_mbyte)
  2350.         curchr = (*mb_ptr2char)(regparse);
  2351. #endif
  2352.     }
  2353.     }
  2354.  
  2355.     return curchr;
  2356. }
  2357.  
  2358. /*
  2359.  * Eat one lexed character.  Do this in a way that we can undo it.
  2360.  */
  2361.     static void
  2362. skipchr()
  2363. {
  2364.     /* peekchr() eats a backslash, do the same here */
  2365.     if (*regparse == '\\')
  2366.     prevchr_len = 1;
  2367.     else
  2368.     prevchr_len = 0;
  2369.     if (regparse[prevchr_len] != NUL)
  2370.     {
  2371. #ifdef FEAT_MBYTE
  2372.     if (has_mbyte)
  2373.         prevchr_len += (*mb_ptr2len_check)(regparse + prevchr_len);
  2374.     else
  2375. #endif
  2376.         ++prevchr_len;
  2377.     }
  2378.     regparse += prevchr_len;
  2379.     prev_at_start = at_start;
  2380.     at_start = FALSE;
  2381.     prevprevchr = prevchr;
  2382.     prevchr = curchr;
  2383.     curchr = nextchr;        /* use previously unget char, or -1 */
  2384.     nextchr = -1;
  2385. }
  2386.  
  2387. /*
  2388.  * Skip a character while keeping the value of prev_at_start for at_start.
  2389.  * prevchr and prevprevchr are also kept.
  2390.  */
  2391.     static void
  2392. skipchr_keepstart()
  2393. {
  2394.     int as = prev_at_start;
  2395.     int pr = prevchr;
  2396.     int prpr = prevprevchr;
  2397.  
  2398.     skipchr();
  2399.     at_start = as;
  2400.     prevchr = pr;
  2401.     prevprevchr = prpr;
  2402. }
  2403.  
  2404.     static int
  2405. getchr()
  2406. {
  2407.     int chr = peekchr();
  2408.  
  2409.     skipchr();
  2410.     return chr;
  2411. }
  2412.  
  2413. /*
  2414.  * put character back.  Works only once!
  2415.  */
  2416.     static void
  2417. ungetchr()
  2418. {
  2419.     nextchr = curchr;
  2420.     curchr = prevchr;
  2421.     prevchr = prevprevchr;
  2422.     at_start = prev_at_start;
  2423.     prev_at_start = FALSE;
  2424.  
  2425.     /* Backup regparse, so that it's at the same position as before the
  2426.      * getchr(). */
  2427.     regparse -= prevchr_len;
  2428. }
  2429.  
  2430. /*
  2431.  * read_limits - Read two integers to be taken as a minimum and maximum.
  2432.  * If the first character is '-', then the range is reversed.
  2433.  * Should end with 'end'.  If minval is missing, zero is default, if maxval is
  2434.  * missing, a very big number is the default.
  2435.  */
  2436.     static int
  2437. read_limits(minval, maxval)
  2438.     long    *minval;
  2439.     long    *maxval;
  2440. {
  2441.     int        reverse = FALSE;
  2442.     char_u    *first_char;
  2443.     long    tmp;
  2444.  
  2445.     if (*regparse == '-')
  2446.     {
  2447.     /* Starts with '-', so reverse the range later */
  2448.     regparse++;
  2449.     reverse = TRUE;
  2450.     }
  2451.     first_char = regparse;
  2452.     *minval = getdigits(®parse);
  2453.     if (*regparse == ',')        /* There is a comma */
  2454.     {
  2455.     if (isdigit(*++regparse))
  2456.         *maxval = getdigits(®parse);
  2457.     else
  2458.         *maxval = MAX_LIMIT;
  2459.     }
  2460.     else if (isdigit(*first_char))
  2461.     *maxval = *minval;        /* It was \{n} or \{-n} */
  2462.     else
  2463.     *maxval = MAX_LIMIT;        /* It was \{} or \{-} */
  2464.     if (*regparse == '\\')
  2465.     regparse++;    /* Allow either \{...} or \{...\} */
  2466.     if (       (*regparse != '}' && *regparse != NUL)
  2467.         || (*maxval == 0 && *minval == 0))
  2468.     {
  2469.     sprintf((char *)IObuff, _("Syntax error in %s{...}"),
  2470.                       reg_magic == MAGIC_ALL ? "" : "\\");
  2471.     EMSG_RET_FAIL(IObuff);
  2472.     }
  2473.  
  2474.     /*
  2475.      * Reverse the range if there was a '-', or make sure it is in the right
  2476.      * order otherwise.
  2477.      */
  2478.     if ((!reverse && *minval > *maxval) || (reverse && *minval < *maxval))
  2479.     {
  2480.     tmp = *minval;
  2481.     *minval = *maxval;
  2482.     *maxval = tmp;
  2483.     }
  2484.     skipchr();        /* let's be friends with the lexer again */
  2485.     return OK;
  2486. }
  2487.  
  2488. /*
  2489.  * vim_regexec and friends
  2490.  */
  2491.  
  2492. /*
  2493.  * Global work variables for vim_regexec().
  2494.  */
  2495.  
  2496. /* The current match-position is remembered with these variables: */
  2497. static linenr_T    reglnum;    /* line number, relative to first line */
  2498. static char_u    *regline;    /* start of current line */
  2499. static char_u    *reginput;    /* current input, points into "regline" */
  2500.  
  2501. static int    need_clear_subexpr;    /* subexpressions still need to be
  2502.                      * cleared */
  2503. #ifdef FEAT_SYN_HL
  2504. static int    need_clear_zsubexpr = FALSE;    /* extmatch subexpressions
  2505.                          * still need to be cleared */
  2506. #endif
  2507.  
  2508. static int    out_of_stack;    /* TRUE when ran out of stack space */
  2509.  
  2510. /*
  2511.  * Structure used to save the current input state, when it needs to be
  2512.  * restored after trying a match.  Used by reg_save() and reg_restore().
  2513.  */
  2514. typedef struct
  2515. {
  2516.     union
  2517.     {
  2518.     char_u    *ptr;    /* reginput pointer, for single-line regexp */
  2519.     lpos_T    pos;    /* reginput pos, for multi-line regexp */
  2520.     } rs_u;
  2521. } regsave_T;
  2522.  
  2523. /* struct to save start/end pointer/position in for \(\) */
  2524. typedef struct
  2525. {
  2526.     union
  2527.     {
  2528.     char_u    *ptr;
  2529.     lpos_T    pos;
  2530.     } se_u;
  2531. } save_se_T;
  2532.  
  2533. static char_u    *reg_getline __ARGS((linenr_T lnum));
  2534. static long    vim_regexec_both __ARGS((char_u *line, colnr_T col));
  2535. static long    regtry __ARGS((regprog_T *prog, colnr_T col));
  2536. static void    cleanup_subexpr __ARGS((void));
  2537. #ifdef FEAT_SYN_HL
  2538. static void    cleanup_zsubexpr __ARGS((void));
  2539. #endif
  2540. static void    reg_nextline __ARGS((void));
  2541. static void    reg_save __ARGS((regsave_T *save));
  2542. static void    reg_restore __ARGS((regsave_T *save));
  2543. static int    reg_save_equal __ARGS((regsave_T *save));
  2544. static void    save_se __ARGS((save_se_T *savep, lpos_T *posp, char_u **pp));
  2545. static void    restore_se __ARGS((save_se_T *savep, lpos_T *posp, char_u **pp));
  2546. static int    re_num_cmp __ARGS((long_u val, char_u *scan));
  2547. static int    regmatch __ARGS((char_u *prog));
  2548. static int    regrepeat __ARGS((char_u *p, long maxcount));
  2549.  
  2550. #ifdef DEBUG
  2551. int        regnarrate = 0;
  2552. #endif
  2553.  
  2554. /*
  2555.  * Internal copy of 'ignorecase'.  It is set at each call to vim_regexec().
  2556.  * Normally it gets the value of "rm_ic" or "rmm_ic", but when the pattern
  2557.  * contains '\c' or '\C' the value is overruled.
  2558.  */
  2559. static int    ireg_ic;
  2560.  
  2561. /*
  2562.  * Sometimes need to save a copy of a line.  Since alloc()/free() is very
  2563.  * slow, we keep one allocated piece of memory and only re-allocate it when
  2564.  * it's too small.  It's freed in vim_regexec_both() when finished.
  2565.  */
  2566. static char_u    *reg_tofree;
  2567. static unsigned    reg_tofreelen;
  2568.  
  2569. /*
  2570.  * These variables are set when executing a regexp to speed up the execution.
  2571.  * Which ones are set depends on whethere a single-line or multi-line match is
  2572.  * done:
  2573.  *            single-line        multi-line
  2574.  * reg_match        ®match_T        NULL
  2575.  * reg_mmatch        NULL            ®mmatch_T
  2576.  * reg_startp        reg_match->startp    <invalid>
  2577.  * reg_endp        reg_match->endp        <invalid>
  2578.  * reg_startpos        <invalid>        reg_mmatch->startpos
  2579.  * reg_endpos        <invalid>        reg_mmatch->endpos
  2580.  * reg_win        NULL            window in which to search
  2581.  * reg_buf        <invalid>        buffer in which to search
  2582.  * reg_firstlnum    <invalid>        first line in which to search
  2583.  * reg_maxline        0            last line nr
  2584.  */
  2585. static regmatch_T    *reg_match;
  2586. static regmmatch_T    *reg_mmatch;
  2587. static char_u        **reg_startp;
  2588. static char_u        **reg_endp;
  2589. static lpos_T        *reg_startpos;
  2590. static lpos_T        *reg_endpos;
  2591. static win_T        *reg_win;
  2592. static buf_T        *reg_buf;
  2593. static linenr_T        reg_firstlnum;
  2594. static linenr_T        reg_maxline;
  2595.  
  2596. /*
  2597.  * Get pointer to the line "lnum", which is relative to "reg_firstlnum".
  2598.  */
  2599.     static char_u *
  2600. reg_getline(lnum)
  2601.     linenr_T    lnum;
  2602. {
  2603.     /* when looking behind for a match/no-match lnum is negative.  But we
  2604.      * can't go before line 1 */
  2605.     if (reg_firstlnum + lnum < 1)
  2606.     return NULL;
  2607.     return ml_get_buf(reg_buf, reg_firstlnum + lnum, FALSE);
  2608. }
  2609.  
  2610. static regsave_T behind_pos;
  2611.  
  2612. #ifdef FEAT_SYN_HL
  2613. static char_u    *reg_startzp[NSUBEXP];    /* Workspace to mark beginning */
  2614. static char_u    *reg_endzp[NSUBEXP];    /*   and end of \z(...\) matches */
  2615. static lpos_T    reg_startzpos[NSUBEXP];    /* idem, beginning pos */
  2616. static lpos_T    reg_endzpos[NSUBEXP];    /* idem, end pos */
  2617. #endif
  2618.  
  2619. /* TRUE if using multi-line regexp. */
  2620. #define REG_MULTI    (reg_match == NULL)
  2621.  
  2622. /*
  2623.  * Match a regexp against a string.
  2624.  * "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
  2625.  * Uses curbuf for line count and 'iskeyword'.
  2626.  *
  2627.  * Return TRUE if there is a match, FALSE if not.
  2628.  */
  2629.     int
  2630. vim_regexec(rmp, line, col)
  2631.     regmatch_T    *rmp;
  2632.     char_u    *line;    /* string to match against */
  2633.     colnr_T    col;    /* column to start looking for match */
  2634. {
  2635.     reg_match = rmp;
  2636.     reg_mmatch = NULL;
  2637.     reg_maxline = 0;
  2638.     reg_win = NULL;
  2639.     ireg_ic = rmp->rm_ic;
  2640.     return (vim_regexec_both(line, col) != 0);
  2641. }
  2642.  
  2643. /*
  2644.  * Match a regexp against multiple lines.
  2645.  * "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
  2646.  * Uses curbuf for line count and 'iskeyword'.
  2647.  *
  2648.  * Return zero if there is no match.  Return number of lines contained in the
  2649.  * match otherwise.
  2650.  */
  2651.     long
  2652. vim_regexec_multi(rmp, win, buf, lnum, col)
  2653.     regmmatch_T    *rmp;
  2654.     win_T    *win;        /* window in which to search or NULL */
  2655.     buf_T    *buf;        /* buffer in which to search */
  2656.     linenr_T    lnum;        /* nr of line to start looking for match */
  2657.     colnr_T    col;        /* column to start looking for match */
  2658. {
  2659.     long    r;
  2660.     buf_T    *save_curbuf = curbuf;
  2661.  
  2662.     reg_match = NULL;
  2663.     reg_mmatch = rmp;
  2664.     reg_buf = buf;
  2665.     reg_win = win;
  2666.     reg_firstlnum = lnum;
  2667.     reg_maxline = reg_buf->b_ml.ml_line_count - lnum;
  2668.     ireg_ic = rmp->rmm_ic;
  2669.  
  2670.     /* Need to switch to buffer "buf" to make vim_iswordc() work. */
  2671.     curbuf = buf;
  2672.     r = vim_regexec_both(NULL, col);
  2673.     curbuf = save_curbuf;
  2674.  
  2675.     return r;
  2676. }
  2677.  
  2678. /*
  2679.  * Match a regexp against a string ("line" points to the string) or multiple
  2680.  * lines ("line" is NULL, use reg_getline()).
  2681.  */
  2682. #ifdef HAVE_SETJMP_H
  2683.     static long
  2684. vim_regexec_both(line_arg, col_arg)
  2685.     char_u    *line_arg;
  2686.     colnr_T    col_arg;    /* column to start looking for match */
  2687. #else
  2688.     static long
  2689. vim_regexec_both(line, col)
  2690.     char_u    *line;
  2691.     colnr_T    col;        /* column to start looking for match */
  2692. #endif
  2693. {
  2694.     regprog_T    *prog;
  2695.     char_u    *s;
  2696.     long    retval;
  2697. #ifdef HAVE_SETJMP_H
  2698.     char_u    *line;
  2699.     colnr_T    col;
  2700. #endif
  2701.  
  2702.     reg_tofree = NULL;
  2703. #ifdef HAVE_SETJMP_H
  2704.     /*
  2705.      * Matching with a regexp may cause a very deep recursive call of
  2706.      * regmatch().  Vim will crash when running out of stack space.  Catch
  2707.      * this here if the system supports it.
  2708.      */
  2709.     mch_startjmp();
  2710.     if (SETJMP(lc_jump_env) != 0)
  2711.     {
  2712.     mch_didjmp();
  2713. #ifdef SIGHASARG
  2714.     if (lc_signal != SIGINT)
  2715. #endif
  2716.         EMSG(_("E361: Crash intercepted; regexp too complex?"));
  2717.     retval = 0L;
  2718.     goto theend;
  2719.     }
  2720.  
  2721.     /* Trick to avoid "might be clobbered by `longjmp'" warning from gcc. */
  2722.     line = line_arg;
  2723.     col = col_arg;
  2724. #endif
  2725.     retval = 0L;
  2726.  
  2727.     if (REG_MULTI)
  2728.     {
  2729.     prog = reg_mmatch->regprog;
  2730.     line = reg_getline((linenr_T)0);
  2731.     reg_startpos = reg_mmatch->startpos;
  2732.     reg_endpos = reg_mmatch->endpos;
  2733.     }
  2734.     else
  2735.     {
  2736.     prog = reg_match->regprog;
  2737.     reg_startp = reg_match->startp;
  2738.     reg_endp = reg_match->endp;
  2739.     }
  2740.  
  2741.     /* Be paranoid... */
  2742.     if (prog == NULL || line == NULL)
  2743.     {
  2744.     EMSG(_(e_null));
  2745.     goto theend;
  2746.     }
  2747.  
  2748.     /* Check validity of program. */
  2749.     if (prog_magic_wrong())
  2750.     goto theend;
  2751.  
  2752.     /* If pattern contains "\c" or "\C": overrule value of ireg_ic */
  2753.     if (prog->regflags & RF_ICASE)
  2754.     ireg_ic = TRUE;
  2755.     else if (prog->regflags & RF_NOICASE)
  2756.     ireg_ic = FALSE;
  2757.  
  2758.     /* If there is a "must appear" string, look for it. */
  2759.     if (prog->regmust != NULL)
  2760.     {
  2761.     int c;
  2762.  
  2763. #ifdef FEAT_MBYTE
  2764.     if (has_mbyte)
  2765.         c = (*mb_ptr2char)(prog->regmust);
  2766.     else
  2767. #endif
  2768.         c = *prog->regmust;
  2769.     s = line + col;
  2770.     while ((s = cstrchr(s, c)) != NULL)
  2771.     {
  2772.         if (cstrncmp(s, prog->regmust, prog->regmlen) == 0)
  2773.         break;        /* Found it. */
  2774. #ifdef FEAT_MBYTE
  2775.         if (has_mbyte)
  2776.         s += (*mb_ptr2len_check)(s);
  2777.         else
  2778. #endif
  2779.         ++s;
  2780.     }
  2781.     if (s == NULL)        /* Not present. */
  2782.         goto theend;
  2783.     }
  2784.  
  2785.     regline = line;
  2786.     reglnum = 0;
  2787.     out_of_stack = FALSE;
  2788.  
  2789.     /* Simplest case: Anchored match need be tried only once. */
  2790.     if (prog->reganch)
  2791.     {
  2792.     int    c;
  2793.  
  2794. #ifdef FEAT_MBYTE
  2795.     if (has_mbyte)
  2796.         c = (*mb_ptr2char)(regline + col);
  2797.     else
  2798. #endif
  2799.         c = regline[col];
  2800.     if (prog->regstart == NUL
  2801.         || prog->regstart == c
  2802.         || (ireg_ic && ((
  2803. #ifdef FEAT_MBYTE
  2804.             (enc_utf8 && utf_fold(prog->regstart) == utf_fold(c)))
  2805.             || (c < 255 && prog->regstart < 255 &&
  2806. #endif
  2807.                 TO_LOWER(prog->regstart) == TO_LOWER(c)))))
  2808.         retval = regtry(prog, col);
  2809.     else
  2810.         retval = 0;
  2811.     }
  2812.     else
  2813.     {
  2814.     /* Messy cases:  unanchored match. */
  2815.     while (!got_int && !out_of_stack)
  2816.     {
  2817.         if (prog->regstart != NUL)
  2818.         {
  2819.         /* Skip until the char we know it must start with. */
  2820.         s = cstrchr(regline + col, prog->regstart);
  2821.         if (s == NULL)
  2822.         {
  2823.             retval = 0;
  2824.             break;
  2825.         }
  2826.         col = (int)(s - regline);
  2827.         }
  2828.  
  2829.         retval = regtry(prog, col);
  2830.         if (retval > 0)
  2831.         break;
  2832.  
  2833.         /* if not currently on the first line, get it again */
  2834.         if (reglnum != 0)
  2835.         {
  2836.         regline = reg_getline((linenr_T)0);
  2837.         reglnum = 0;
  2838.         }
  2839.         if (regline[col] == NUL)
  2840.         break;
  2841. #ifdef FEAT_MBYTE
  2842.         if (has_mbyte)
  2843.         col += (*mb_ptr2len_check)(regline + col);
  2844.         else
  2845. #endif
  2846.         ++col;
  2847.     }
  2848.     }
  2849.  
  2850.     if (out_of_stack)
  2851.     EMSG(_("E363: pattern caused out-of-stack error"));
  2852.  
  2853. theend:
  2854.     /* Didn't find a match. */
  2855.     vim_free(reg_tofree);
  2856. #ifdef HAVE_SETJMP_H
  2857.     mch_endjmp();
  2858. #endif
  2859.     return retval;
  2860. }
  2861.  
  2862. #ifdef FEAT_SYN_HL
  2863. static reg_extmatch_T *make_extmatch __ARGS((void));
  2864.  
  2865. /*
  2866.  * Create a new extmatch and mark it as referenced once.
  2867.  */
  2868.     static reg_extmatch_T *
  2869. make_extmatch()
  2870. {
  2871.     reg_extmatch_T    *em;
  2872.  
  2873.     em = (reg_extmatch_T *)alloc_clear((unsigned)sizeof(reg_extmatch_T));
  2874.     if (em != NULL)
  2875.     em->refcnt = 1;
  2876.     return em;
  2877. }
  2878.  
  2879. /*
  2880.  * Add a reference to an extmatch.
  2881.  */
  2882.     reg_extmatch_T *
  2883. ref_extmatch(em)
  2884.     reg_extmatch_T    *em;
  2885. {
  2886.     if (em != NULL)
  2887.     em->refcnt++;
  2888.     return em;
  2889. }
  2890.  
  2891. /*
  2892.  * Remove a reference to an extmatch.  If there are no references left, free
  2893.  * the info.
  2894.  */
  2895.     void
  2896. unref_extmatch(em)
  2897.     reg_extmatch_T    *em;
  2898. {
  2899.     int i;
  2900.  
  2901.     if (em != NULL && --em->refcnt <= 0)
  2902.     {
  2903.     for (i = 0; i < NSUBEXP; ++i)
  2904.         vim_free(em->matches[i]);
  2905.     vim_free(em);
  2906.     }
  2907. }
  2908. #endif
  2909.  
  2910. /*
  2911.  * regtry - try match of "prog" with at regline["col"].
  2912.  * Returns 0 for failure, number of lines contained in the match otherwise.
  2913.  */
  2914.     static long
  2915. regtry(prog, col)
  2916.     regprog_T    *prog;
  2917.     colnr_T    col;
  2918. {
  2919.     reginput = regline + col;
  2920.     need_clear_subexpr = TRUE;
  2921. #ifdef FEAT_SYN_HL
  2922.     /* Clear the external match subpointers if necessary. */
  2923.     if (prog->reghasz == REX_SET)
  2924.     need_clear_zsubexpr = TRUE;
  2925. #endif
  2926.  
  2927.     if (regmatch(prog->program + 1))
  2928.     {
  2929.     cleanup_subexpr();
  2930.     if (REG_MULTI)
  2931.     {
  2932.         if (reg_startpos[0].lnum < 0)
  2933.         {
  2934.         reg_startpos[0].lnum = 0;
  2935.         reg_startpos[0].col = col;
  2936.         }
  2937.         if (reg_endpos[0].lnum < 0)
  2938.         {
  2939.         reg_endpos[0].lnum = reglnum;
  2940.         reg_endpos[0].col = (int)(reginput - regline);
  2941.         }
  2942.     }
  2943.     else
  2944.     {
  2945.         if (reg_startp[0] == NULL)
  2946.         reg_startp[0] = regline + col;
  2947.         if (reg_endp[0] == NULL)
  2948.         reg_endp[0] = reginput;
  2949.     }
  2950. #ifdef FEAT_SYN_HL
  2951.     /* Package any found \z(...\) matches for export. Default is none. */
  2952.     unref_extmatch(re_extmatch_out);
  2953.     re_extmatch_out = NULL;
  2954.  
  2955.     if (prog->reghasz == REX_SET)
  2956.     {
  2957.         int        i;
  2958.  
  2959.         cleanup_zsubexpr();
  2960.         re_extmatch_out = make_extmatch();
  2961.         for (i = 0; i < NSUBEXP; i++)
  2962.         {
  2963.         if (REG_MULTI)
  2964.         {
  2965.             /* Only accept single line matches. */
  2966.             if (reg_startzpos[i].lnum >= 0
  2967.                 && reg_endzpos[i].lnum == reg_startzpos[i].lnum)
  2968.             re_extmatch_out->matches[i] =
  2969.                 vim_strnsave(reg_getline(reg_startzpos[i].lnum)
  2970.                                + reg_startzpos[i].col,
  2971.                     reg_endzpos[i].col - reg_startzpos[i].col);
  2972.         }
  2973.         else
  2974.         {
  2975.             if (reg_startzp[i] != NULL && reg_endzp[i] != NULL)
  2976.             re_extmatch_out->matches[i] =
  2977.                 vim_strnsave(reg_startzp[i],
  2978.                     (int)(reg_endzp[i] - reg_startzp[i]));
  2979.         }
  2980.         }
  2981.     }
  2982. #endif
  2983.     return 1 + reglnum;
  2984.     }
  2985.     return 0;
  2986. }
  2987.  
  2988. #ifdef FEAT_MBYTE
  2989. /* multi-byte: advance reginput with a function */
  2990. # define ADVANCE_REGINPUT() advance_reginput()
  2991.  
  2992. static void advance_reginput __ARGS((void));
  2993. static int reg_prev_class __ARGS((void));
  2994.  
  2995.     static void
  2996. advance_reginput()
  2997. {
  2998.     if (has_mbyte)
  2999.     reginput += (*mb_ptr2len_check)(reginput);
  3000.     else
  3001.     ++reginput;
  3002. }
  3003.  
  3004. /*
  3005.  * Get class of previous character.
  3006.  */
  3007.     static int
  3008. reg_prev_class()
  3009. {
  3010.     if (reginput > regline)
  3011.     return mb_get_class(reginput - 1
  3012.                      - (*mb_head_off)(regline, reginput - 1));
  3013.     return -1;
  3014. }
  3015.  
  3016. #else
  3017. /* No multi-byte: It's too simple to make a function for. */
  3018. # define ADVANCE_REGINPUT() ++reginput
  3019. #endif
  3020.  
  3021. /*
  3022.  * The arguments from BRACE_LIMITS are stored here.  They are actually local
  3023.  * to regmatch(), but they are here to reduce the amount of stack space used
  3024.  * (it can be called recursively many times).
  3025.  */
  3026. static long    bl_minval;
  3027. static long    bl_maxval;
  3028.  
  3029. /*
  3030.  * regmatch - main matching routine
  3031.  *
  3032.  * Conceptually the strategy is simple: Check to see whether the current
  3033.  * node matches, call self recursively to see whether the rest matches,
  3034.  * and then act accordingly.  In practice we make some effort to avoid
  3035.  * recursion, in particular by going through "ordinary" nodes (that don't
  3036.  * need to know whether the rest of the match failed) by a loop instead of
  3037.  * by recursion.
  3038.  *
  3039.  * Returns TRUE when there is a match.  Leaves reginput and reglnum just after
  3040.  * the last matched character.
  3041.  * Returns FALSE when there is no match.  Leaves reginput and reglnum in an
  3042.  * undefined state!
  3043.  */
  3044.     static int
  3045. regmatch(scan)
  3046.     char_u    *scan;        /* Current node. */
  3047. {
  3048.     char_u    *next;        /* Next node. */
  3049.     int        op;
  3050.     int        c;
  3051.  
  3052. #ifdef HAVE_GETRLIMIT
  3053.     /* Check if we are running out of stack space.  Could be caused by
  3054.      * recursively calling ourselves. */
  3055.     if (out_of_stack || mch_stackcheck((char *)&op) == FAIL)
  3056.     {
  3057.     out_of_stack = TRUE;
  3058.     return FALSE;
  3059.     }
  3060. #endif
  3061.  
  3062.     /* Some patterns my cause a long time to match, even though they are not
  3063.      * illegal.  E.g., "\([a-z]\+\)\+Q".  Allow breaking them with CTRL-C. */
  3064.     fast_breakcheck();
  3065.  
  3066. #ifdef DEBUG
  3067.     if (scan != NULL && regnarrate)
  3068.     {
  3069.     mch_errmsg(regprop(scan));
  3070.     mch_errmsg("(\n");
  3071.     }
  3072. #endif
  3073.     while (scan != NULL)
  3074.     {
  3075.     if (got_int)
  3076.         return FALSE;
  3077. #ifdef DEBUG
  3078.     if (regnarrate)
  3079.     {
  3080.         mch_errmsg(regprop(scan));
  3081.         mch_errmsg("...\n");
  3082. # ifdef FEAT_SYN_HL
  3083.         if (re_extmatch_in != NULL)
  3084.         {
  3085.         int i;
  3086.  
  3087.         mch_errmsg(_("External submatches:\n"));
  3088.         for (i = 0; i < NSUBEXP; i++)
  3089.         {
  3090.             mch_errmsg("    \"");
  3091.             if (re_extmatch_in->matches[i] != NULL)
  3092.             mch_errmsg(re_extmatch_in->matches[i]);
  3093.             mch_errmsg("\"\n");
  3094.         }
  3095.         }
  3096. # endif
  3097.     }
  3098. #endif
  3099.     next = regnext(scan);
  3100.  
  3101.     op = OP(scan);
  3102.     /* Check for character class with NL added. */
  3103.     if (WITH_NL(op) && *reginput == NUL && reglnum < reg_maxline)
  3104.     {
  3105.         reg_nextline();
  3106.     }
  3107.     else
  3108.     {
  3109.       if (WITH_NL(op))
  3110.         op -= ADD_NL;
  3111. #ifdef FEAT_MBYTE
  3112.       if (has_mbyte)
  3113.           c = (*mb_ptr2char)(reginput);
  3114.       else
  3115. #endif
  3116.           c = *reginput;
  3117.       switch (op)
  3118.       {
  3119.       case BOL:
  3120.         if (reginput != regline)
  3121.         return FALSE;
  3122.         break;
  3123.  
  3124.       case EOL:
  3125.         if (c != NUL)
  3126.         return FALSE;
  3127.         break;
  3128.  
  3129.       case RE_BOF:
  3130.         /* Passing -1 to the getline() function provided for the search
  3131.          * should always return NULL if the current line is the first
  3132.          * line of the file. */
  3133.         if (reglnum != 0 || reginput != regline
  3134.             || (REG_MULTI && reg_getline((linenr_T)-1) != NULL))
  3135.         return FALSE;
  3136.         break;
  3137.  
  3138.       case RE_EOF:
  3139.         if (reglnum != reg_maxline || c != NUL)
  3140.         return FALSE;
  3141.         break;
  3142.  
  3143.       case CURSOR:
  3144.         /* Check if the buffer is in a window and compare the
  3145.          * reg_win->w_cursor position to the match position. */
  3146.         if (reg_win == NULL
  3147.             || (reglnum + reg_firstlnum != reg_win->w_cursor.lnum)
  3148.             || ((colnr_T)(reginput - regline) != reg_win->w_cursor.col))
  3149.         return FALSE;
  3150.         break;
  3151.  
  3152.       case RE_LNUM:
  3153.         if (!REG_MULTI || !re_num_cmp((long_u)(reglnum + reg_firstlnum),
  3154.                                     scan))
  3155.         return FALSE;
  3156.         break;
  3157.  
  3158.       case RE_COL:
  3159.         if (!re_num_cmp((long_u)(reginput - regline) + 1, scan))
  3160.         return FALSE;
  3161.         break;
  3162.  
  3163.       case RE_VCOL:
  3164.         if (!re_num_cmp((long_u)win_linetabsize(
  3165.                 reg_win == NULL ? curwin : reg_win,
  3166.                 regline, (colnr_T)(reginput - regline)) + 1, scan))
  3167.         return FALSE;
  3168.         break;
  3169.  
  3170.       case BOW:    /* \<word; reginput points to w */
  3171.         if (c == NUL)    /* Can't match at end of line */
  3172.         return FALSE;
  3173. #ifdef FEAT_MBYTE
  3174.         if (has_mbyte)
  3175.         {
  3176.         int this_class;
  3177.  
  3178.         /* Get class of current and previous char (if it exists). */
  3179.         this_class = mb_get_class(reginput);
  3180.         if (this_class <= 1)
  3181.             return FALSE;    /* not on a word at all */
  3182.         if (reg_prev_class() == this_class)
  3183.             return FALSE;    /* previous char is in same word */
  3184.         }
  3185. #endif
  3186.         else
  3187.         {
  3188.         if (!vim_iswordc(c)
  3189.             || (reginput > regline && vim_iswordc(reginput[-1])))
  3190.             return FALSE;
  3191.         }
  3192.         break;
  3193.  
  3194.       case EOW:    /* word\>; reginput points after d */
  3195.         if (reginput == regline)    /* Can't match at start of line */
  3196.         return FALSE;
  3197. #ifdef FEAT_MBYTE
  3198.         if (has_mbyte)
  3199.         {
  3200.         int this_class, prev_class;
  3201.  
  3202.         /* Get class of current and previous char (if it exists). */
  3203.         this_class = mb_get_class(reginput);
  3204.         prev_class = reg_prev_class();
  3205.         if (this_class == prev_class)
  3206.             return FALSE;
  3207.         if (prev_class == 0 || prev_class == 1)
  3208.             return FALSE;
  3209.         }
  3210.         else
  3211. #endif
  3212.         {
  3213.         if (!vim_iswordc(reginput[-1]))
  3214.             return FALSE;
  3215.         if (reginput[0] != NUL && vim_iswordc(c))
  3216.             return FALSE;
  3217.         }
  3218.         break; /* Matched with EOW */
  3219.  
  3220.       case ANY:
  3221.         if (c == NUL)
  3222.         return FALSE;
  3223.         ADVANCE_REGINPUT();
  3224.         break;
  3225.  
  3226.       case IDENT:
  3227.         if (!vim_isIDc(c))
  3228.         return FALSE;
  3229.         ADVANCE_REGINPUT();
  3230.         break;
  3231.  
  3232.       case SIDENT:
  3233.         if (isdigit(*reginput) || !vim_isIDc(c))
  3234.         return FALSE;
  3235.         ADVANCE_REGINPUT();
  3236.         break;
  3237.  
  3238.       case KWORD:
  3239.         if (!vim_iswordp(reginput))
  3240.         return FALSE;
  3241.         ADVANCE_REGINPUT();
  3242.         break;
  3243.  
  3244.       case SKWORD:
  3245.         if (isdigit(*reginput) || !vim_iswordp(reginput))
  3246.         return FALSE;
  3247.         ADVANCE_REGINPUT();
  3248.         break;
  3249.  
  3250.       case FNAME:
  3251.         if (!vim_isfilec(c))
  3252.         return FALSE;
  3253.         ADVANCE_REGINPUT();
  3254.         break;
  3255.  
  3256.       case SFNAME:
  3257.         if (isdigit(*reginput) || !vim_isfilec(c))
  3258.         return FALSE;
  3259.         ADVANCE_REGINPUT();
  3260.         break;
  3261.  
  3262.       case PRINT:
  3263.         if (ptr2cells(reginput) != 1)
  3264.         return FALSE;
  3265.         ADVANCE_REGINPUT();
  3266.         break;
  3267.  
  3268.       case SPRINT:
  3269.         if (isdigit(*reginput) || ptr2cells(reginput) != 1)
  3270.         return FALSE;
  3271.         ADVANCE_REGINPUT();
  3272.         break;
  3273.  
  3274.       case WHITE:
  3275.         if (!vim_iswhite(c))
  3276.         return FALSE;
  3277.         ADVANCE_REGINPUT();
  3278.         break;
  3279.  
  3280.       case NWHITE:
  3281.         if (c == NUL || vim_iswhite(c))
  3282.         return FALSE;
  3283.         ADVANCE_REGINPUT();
  3284.         break;
  3285.  
  3286.       case DIGIT:
  3287.         if (!ri_digit(c))
  3288.         return FALSE;
  3289.         ADVANCE_REGINPUT();
  3290.         break;
  3291.  
  3292.       case NDIGIT:
  3293.         if (c == NUL || ri_digit(c))
  3294.         return FALSE;
  3295.         ADVANCE_REGINPUT();
  3296.         break;
  3297.  
  3298.       case HEX:
  3299.         if (!ri_hex(c))
  3300.         return FALSE;
  3301.         ADVANCE_REGINPUT();
  3302.         break;
  3303.  
  3304.       case NHEX:
  3305.         if (c == NUL || ri_hex(c))
  3306.         return FALSE;
  3307.         ADVANCE_REGINPUT();
  3308.         break;
  3309.  
  3310.       case OCTAL:
  3311.         if (!ri_octal(c))
  3312.         return FALSE;
  3313.         ADVANCE_REGINPUT();
  3314.         break;
  3315.  
  3316.       case NOCTAL:
  3317.         if (c == NUL || ri_octal(c))
  3318.         return FALSE;
  3319.         ADVANCE_REGINPUT();
  3320.         break;
  3321.  
  3322.       case WORD:
  3323.         if (!ri_word(c))
  3324.         return FALSE;
  3325.         ADVANCE_REGINPUT();
  3326.         break;
  3327.  
  3328.       case NWORD:
  3329.         if (c == NUL || ri_word(c))
  3330.         return FALSE;
  3331.         ADVANCE_REGINPUT();
  3332.         break;
  3333.  
  3334.       case HEAD:
  3335.         if (!ri_head(c))
  3336.         return FALSE;
  3337.         ADVANCE_REGINPUT();
  3338.         break;
  3339.  
  3340.       case NHEAD:
  3341.         if (c == NUL || ri_head(c))
  3342.         return FALSE;
  3343.         ADVANCE_REGINPUT();
  3344.         break;
  3345.  
  3346.       case ALPHA:
  3347.         if (!ri_alpha(c))
  3348.         return FALSE;
  3349.         ADVANCE_REGINPUT();
  3350.         break;
  3351.  
  3352.       case NALPHA:
  3353.         if (c == NUL || ri_alpha(c))
  3354.         return FALSE;
  3355.         ADVANCE_REGINPUT();
  3356.         break;
  3357.  
  3358.       case LOWER:
  3359.         if (!ri_lower(c))
  3360.         return FALSE;
  3361.         ADVANCE_REGINPUT();
  3362.         break;
  3363.  
  3364.       case NLOWER:
  3365.         if (c == NUL || ri_lower(c))
  3366.         return FALSE;
  3367.         ADVANCE_REGINPUT();
  3368.         break;
  3369.  
  3370.       case UPPER:
  3371.         if (!ri_upper(c))
  3372.         return FALSE;
  3373.         ADVANCE_REGINPUT();
  3374.         break;
  3375.  
  3376.       case NUPPER:
  3377.         if (c == NUL || ri_upper(c))
  3378.         return FALSE;
  3379.         ADVANCE_REGINPUT();
  3380.         break;
  3381.  
  3382.       case EXACTLY:
  3383.         {
  3384.         int    len;
  3385.         char_u    *opnd;
  3386.  
  3387.         opnd = OPERAND(scan);
  3388.         /* Inline the first byte, for speed. */
  3389.         if (*opnd != *reginput
  3390.             && (!ireg_ic || (
  3391. #ifdef FEAT_MBYTE
  3392.                 !enc_utf8 &&
  3393. #endif
  3394.                 TO_LOWER(*opnd) != TO_LOWER(*reginput))))
  3395.             return FALSE;
  3396.         if (opnd[1] == NUL
  3397. #ifdef FEAT_MBYTE
  3398.                 && !(enc_utf8 && ireg_ic)
  3399. #endif
  3400.             )
  3401.             ++reginput;        /* matched a single char */
  3402.         else
  3403.         {
  3404.             len = (int)STRLEN(opnd);
  3405.             /* Need to match first byte again for multi-byte. */
  3406.             if (cstrncmp(opnd, reginput, len) != 0)
  3407.             return FALSE;
  3408. #ifdef FEAT_MBYTE
  3409.             /* Check for following composing character. */
  3410.             if (enc_utf8 && utf_iscomposing(
  3411.                            utf_ptr2char(reginput + len)))
  3412.             return FALSE;
  3413. #endif
  3414.             reginput += len;
  3415.         }
  3416.         }
  3417.         break;
  3418.  
  3419.       case ANYOF:
  3420.       case ANYBUT:
  3421.         if (c == NUL)
  3422.         return FALSE;
  3423.         if ((cstrchr(OPERAND(scan), c) == NULL) == (op == ANYOF))
  3424.         return FALSE;
  3425.         ADVANCE_REGINPUT();
  3426.         break;
  3427.  
  3428. #ifdef FEAT_MBYTE
  3429.       case MULTIBYTECODE:
  3430.         if (has_mbyte)
  3431.         {
  3432.         int    i, len;
  3433.         char_u    *opnd;
  3434.  
  3435.         opnd = OPERAND(scan);
  3436.         /* Safety check (just in case 'encoding' was changed since
  3437.          * compiling the program). */
  3438.         if ((len = (*mb_ptr2len_check)(opnd)) < 2)
  3439.             return FALSE;
  3440.         for (i = 0; i < len; ++i)
  3441.             if (opnd[i] != reginput[i])
  3442.             return FALSE;
  3443.         reginput += len;
  3444.         }
  3445.         else
  3446.         return FALSE;
  3447.         break;
  3448. #endif
  3449.  
  3450.       case NOTHING:
  3451.         break;
  3452.  
  3453.       case BACK:
  3454.         break;
  3455.  
  3456.       case MOPEN + 0:   /* Match start: \zs */
  3457.       case MOPEN + 1:   /* \( */
  3458.       case MOPEN + 2:
  3459.       case MOPEN + 3:
  3460.       case MOPEN + 4:
  3461.       case MOPEN + 5:
  3462.       case MOPEN + 6:
  3463.       case MOPEN + 7:
  3464.       case MOPEN + 8:
  3465.       case MOPEN + 9:
  3466.         {
  3467.         int        no;
  3468.         save_se_T    save;
  3469.  
  3470.         no = op - MOPEN;
  3471.         cleanup_subexpr();
  3472.         save_se(&save, ®_startpos[no], ®_startp[no]);
  3473.  
  3474.         if (regmatch(next))
  3475.             return TRUE;
  3476.  
  3477.         restore_se(&save, ®_startpos[no], ®_startp[no]);
  3478.         return FALSE;
  3479.         }
  3480.         /* break; Not Reached */
  3481.  
  3482.       case NOPEN:        /* \%( */
  3483.       case NCLOSE:        /* \) after \%( */
  3484.         if (regmatch(next))
  3485.             return TRUE;
  3486.         return FALSE;
  3487.         /* break; Not Reached */
  3488.  
  3489. #ifdef FEAT_SYN_HL
  3490.       case ZOPEN + 1:
  3491.       case ZOPEN + 2:
  3492.       case ZOPEN + 3:
  3493.       case ZOPEN + 4:
  3494.       case ZOPEN + 5:
  3495.       case ZOPEN + 6:
  3496.       case ZOPEN + 7:
  3497.       case ZOPEN + 8:
  3498.       case ZOPEN + 9:
  3499.         {
  3500.         int        no;
  3501.         save_se_T    save;
  3502.  
  3503.         no = op - ZOPEN;
  3504.         cleanup_zsubexpr();
  3505.         save_se(&save, ®_startzpos[no], ®_startzp[no]);
  3506.  
  3507.         if (regmatch(next))
  3508.             return TRUE;
  3509.  
  3510.         restore_se(&save, ®_startzpos[no], ®_startzp[no]);
  3511.         return FALSE;
  3512.         }
  3513.         /* break; Not Reached */
  3514. #endif
  3515.  
  3516.       case MCLOSE + 0:  /* Match end: \ze */
  3517.       case MCLOSE + 1:  /* \) */
  3518.       case MCLOSE + 2:
  3519.       case MCLOSE + 3:
  3520.       case MCLOSE + 4:
  3521.       case MCLOSE + 5:
  3522.       case MCLOSE + 6:
  3523.       case MCLOSE + 7:
  3524.       case MCLOSE + 8:
  3525.       case MCLOSE + 9:
  3526.         {
  3527.         int        no;
  3528.         save_se_T    save;
  3529.  
  3530.         no = op - MCLOSE;
  3531.         cleanup_subexpr();
  3532.         save_se(&save, ®_endpos[no], ®_endp[no]);
  3533.  
  3534.         if (regmatch(next))
  3535.             return TRUE;
  3536.  
  3537.         restore_se(&save, ®_endpos[no], ®_endp[no]);
  3538.         return FALSE;
  3539.         }
  3540.         /* break; Not Reached */
  3541.  
  3542. #ifdef FEAT_SYN_HL
  3543.       case ZCLOSE + 1:  /* \) after \z( */
  3544.       case ZCLOSE + 2:
  3545.       case ZCLOSE + 3:
  3546.       case ZCLOSE + 4:
  3547.       case ZCLOSE + 5:
  3548.       case ZCLOSE + 6:
  3549.       case ZCLOSE + 7:
  3550.       case ZCLOSE + 8:
  3551.       case ZCLOSE + 9:
  3552.         {
  3553.         int        no;
  3554.         save_se_T    save;
  3555.  
  3556.         no = op - ZCLOSE;
  3557.         cleanup_zsubexpr();
  3558.         save_se(&save, ®_endzpos[no], ®_endzp[no]);
  3559.  
  3560.         if (regmatch(next))
  3561.             return TRUE;
  3562.  
  3563.         restore_se(&save, ®_endzpos[no], ®_endzp[no]);
  3564.         return FALSE;
  3565.         }
  3566.         /* break; Not Reached */
  3567. #endif
  3568.  
  3569.       case BACKREF + 1:
  3570.       case BACKREF + 2:
  3571.       case BACKREF + 3:
  3572.       case BACKREF + 4:
  3573.       case BACKREF + 5:
  3574.       case BACKREF + 6:
  3575.       case BACKREF + 7:
  3576.       case BACKREF + 8:
  3577.       case BACKREF + 9:
  3578.         {
  3579.         int        no;
  3580.         int        len;
  3581.         linenr_T    clnum;
  3582.         colnr_T        ccol;
  3583.         char_u        *p;
  3584.  
  3585.         no = op - BACKREF;
  3586.         cleanup_subexpr();
  3587.         if (!REG_MULTI)        /* Single-line regexp */
  3588.         {
  3589.             if (reg_endp[no] == NULL)
  3590.             {
  3591.             /* Backref was not set: Match an empty string. */
  3592.             len = 0;
  3593.             }
  3594.             else
  3595.             {
  3596.             /* Compare current input with back-ref in the same
  3597.              * line. */
  3598.             len = (int)(reg_endp[no] - reg_startp[no]);
  3599.             if (cstrncmp(reg_startp[no], reginput, len) != 0)
  3600.                 return FALSE;
  3601.             }
  3602.         }
  3603.         else                /* Multi-line regexp */
  3604.         {
  3605.             if (reg_endpos[no].lnum < 0)
  3606.             {
  3607.             /* Backref was not set: Match an empty string. */
  3608.             len = 0;
  3609.             }
  3610.             else
  3611.             {
  3612.             if (reg_startpos[no].lnum == reglnum
  3613.                 && reg_endpos[no].lnum == reglnum)
  3614.             {
  3615.                 /* Compare back-ref within the current line. */
  3616.                 len = reg_endpos[no].col - reg_startpos[no].col;
  3617.                 if (cstrncmp(regline + reg_startpos[no].col,
  3618.                               reginput, len) != 0)
  3619.                 return FALSE;
  3620.             }
  3621.             else
  3622.             {
  3623.                 /* Messy situation: Need to compare between two
  3624.                  * lines. */
  3625.                 ccol = reg_startpos[no].col;
  3626.                 clnum = reg_startpos[no].lnum;
  3627.                 for (;;)
  3628.                 {
  3629.                 /* Since getting one line may invalidate
  3630.                  * the other, need to make copy.  Slow! */
  3631.                 if (regline != reg_tofree)
  3632.                 {
  3633.                     len = (int)STRLEN(regline);
  3634.                     if (reg_tofree == NULL
  3635.                          || len >= (int)reg_tofreelen)
  3636.                     {
  3637.                     len += 50;    /* get some extra */
  3638.                     vim_free(reg_tofree);
  3639.                     reg_tofree = alloc(len);
  3640.                     if (reg_tofree == NULL)
  3641.                         return FALSE; /* out of memory! */
  3642.                     reg_tofreelen = len;
  3643.                     }
  3644.                     STRCPY(reg_tofree, regline);
  3645.                     reginput = reg_tofree
  3646.                                + (reginput - regline);
  3647.                     regline = reg_tofree;
  3648.                 }
  3649.  
  3650.                 /* Get the line to compare with. */
  3651.                 p = reg_getline(clnum);
  3652.                 if (clnum == reg_endpos[no].lnum)
  3653.                     len = reg_endpos[no].col - ccol;
  3654.                 else
  3655.                     len = (int)STRLEN(p + ccol);
  3656.  
  3657.                 if (cstrncmp(p + ccol, reginput, len) != 0)
  3658.                     return FALSE;    /* doesn't match */
  3659.                 if (clnum == reg_endpos[no].lnum)
  3660.                     break;        /* match and at end! */
  3661.                 if (reglnum == reg_maxline)
  3662.                     return FALSE;    /* text too short */
  3663.  
  3664.                 /* Advance to next line. */
  3665.                 reg_nextline();
  3666.                 ++clnum;
  3667.                 ccol = 0;
  3668.                 if (got_int)
  3669.                     return FALSE;
  3670.                 }
  3671.  
  3672.                 /* found a match!  Note that regline may now point
  3673.                  * to a copy of the line, that should not matter. */
  3674.             }
  3675.             }
  3676.         }
  3677.  
  3678.         /* Matched the backref, skip over it. */
  3679.         reginput += len;
  3680.         }
  3681.         break;
  3682.  
  3683. #ifdef FEAT_SYN_HL
  3684.       case ZREF + 1:
  3685.       case ZREF + 2:
  3686.       case ZREF + 3:
  3687.       case ZREF + 4:
  3688.       case ZREF + 5:
  3689.       case ZREF + 6:
  3690.       case ZREF + 7:
  3691.       case ZREF + 8:
  3692.       case ZREF + 9:
  3693.         {
  3694.         int    no;
  3695.         int    len;
  3696.  
  3697.         cleanup_zsubexpr();
  3698.         no = op - ZREF;
  3699.         if (re_extmatch_in != NULL
  3700.             && re_extmatch_in->matches[no] != NULL)
  3701.         {
  3702.             len = (int)STRLEN(re_extmatch_in->matches[no]);
  3703.             if (cstrncmp(re_extmatch_in->matches[no],
  3704.                               reginput, len) != 0)
  3705.             return FALSE;
  3706.             reginput += len;
  3707.         }
  3708.         else
  3709.         {
  3710.             /* Backref was not set: Match an empty string. */
  3711.         }
  3712.         }
  3713.         break;
  3714. #endif
  3715.  
  3716.       case BRANCH:
  3717.         {
  3718.         if (OP(next) != BRANCH) /* No choice. */
  3719.             next = OPERAND(scan);    /* Avoid recursion. */
  3720.         else
  3721.         {
  3722.             regsave_T    save;
  3723.  
  3724.             do
  3725.             {
  3726.             reg_save(&save);
  3727.             if (regmatch(OPERAND(scan)))
  3728.                 return TRUE;
  3729.             reg_restore(&save);
  3730.             scan = regnext(scan);
  3731.             } while (scan != NULL && OP(scan) == BRANCH);
  3732.             return FALSE;
  3733.             /* NOTREACHED */
  3734.         }
  3735.         }
  3736.         break;
  3737.  
  3738.       case BRACE_LIMITS:
  3739.         {
  3740.         int    no;
  3741.  
  3742.         if (OP(next) == BRACE_SIMPLE)
  3743.         {
  3744.             bl_minval = OPERAND_MIN(scan);
  3745.             bl_maxval = OPERAND_MAX(scan);
  3746.         }
  3747.         else if (OP(next) >= BRACE_COMPLEX
  3748.             && OP(next) < BRACE_COMPLEX + 10)
  3749.         {
  3750.             no = OP(next) - BRACE_COMPLEX;
  3751.             brace_min[no] = OPERAND_MIN(scan);
  3752.             brace_max[no] = OPERAND_MAX(scan);
  3753.             brace_count[no] = 0;
  3754.         }
  3755.         else
  3756.         {
  3757.             EMSG(_(e_internal));        /* Shouldn't happen */
  3758.             return FALSE;
  3759.         }
  3760.         }
  3761.         break;
  3762.  
  3763.       case BRACE_COMPLEX + 0:
  3764.       case BRACE_COMPLEX + 1:
  3765.       case BRACE_COMPLEX + 2:
  3766.       case BRACE_COMPLEX + 3:
  3767.       case BRACE_COMPLEX + 4:
  3768.       case BRACE_COMPLEX + 5:
  3769.       case BRACE_COMPLEX + 6:
  3770.       case BRACE_COMPLEX + 7:
  3771.       case BRACE_COMPLEX + 8:
  3772.       case BRACE_COMPLEX + 9:
  3773.         {
  3774.         int        no;
  3775.         regsave_T    save;
  3776.  
  3777.         no = op - BRACE_COMPLEX;
  3778.         ++brace_count[no];
  3779.  
  3780.         /* If not matched enough times yet, try one more */
  3781.         if (brace_count[no] <= (brace_min[no] <= brace_max[no]
  3782.                     ? brace_min[no] : brace_max[no]))
  3783.         {
  3784.             reg_save(&save);
  3785.             if (regmatch(OPERAND(scan)))
  3786.             return TRUE;
  3787.             reg_restore(&save);
  3788.             --brace_count[no];    /* failed, decrement match count */
  3789.             return FALSE;
  3790.         }
  3791.  
  3792.         /* If matched enough times, may try matching some more */
  3793.         if (brace_min[no] <= brace_max[no])
  3794.         {
  3795.             /* Range is the normal way around, use longest match */
  3796.             if (brace_count[no] <= brace_max[no])
  3797.             {
  3798.             reg_save(&save);
  3799.             if (regmatch(OPERAND(scan)))
  3800.                 return TRUE;    /* matched some more times */
  3801.             reg_restore(&save);
  3802.             --brace_count[no];  /* matched just enough times */
  3803.             /* continue with the items after \{} */
  3804.             }
  3805.         }
  3806.         else
  3807.         {
  3808.             /* Range is backwards, use shortest match first */
  3809.             if (brace_count[no] <= brace_min[no])
  3810.             {
  3811.             reg_save(&save);
  3812.             if (regmatch(next))
  3813.                 return TRUE;
  3814.             reg_restore(&save);
  3815.             next = OPERAND(scan);
  3816.             /* must try to match one more item */
  3817.             }
  3818.         }
  3819.         }
  3820.         break;
  3821.  
  3822.       case BRACE_SIMPLE:
  3823.       case STAR:
  3824.       case PLUS:
  3825.         {
  3826.         int        nextb;        /* next byte */
  3827.         int        nextb_ic;    /* next byte reverse case */
  3828.         long        count;
  3829.         regsave_T    save;
  3830.         long        minval;
  3831.         long        maxval;
  3832.  
  3833.         /*
  3834.          * Lookahead to avoid useless match attempts when we know
  3835.          * what character comes next.
  3836.          */
  3837.         if (OP(next) == EXACTLY)
  3838.         {
  3839.             nextb = *OPERAND(next);
  3840.             if (ireg_ic)
  3841.             {
  3842.             if (isupper(nextb))
  3843.                 nextb_ic = TO_LOWER(nextb);
  3844.             else
  3845.                 nextb_ic = TO_UPPER(nextb);
  3846.             }
  3847.             else
  3848.             nextb_ic = nextb;
  3849.         }
  3850.         else
  3851.         {
  3852.             nextb = NUL;
  3853.             nextb_ic = NUL;
  3854.         }
  3855.         if (op != BRACE_SIMPLE)
  3856.         {
  3857.             minval = (op == STAR) ? 0 : 1;
  3858.             maxval = MAX_LIMIT;
  3859.         }
  3860.         else
  3861.         {
  3862.             minval = bl_minval;
  3863.             maxval = bl_maxval;
  3864.         }
  3865.  
  3866.         /*
  3867.          * When maxval > minval, try matching as much as possible, up
  3868.          * to maxval.  When maxval < minval, try matching at least the
  3869.          * minimal number (since the range is backwards, that's also
  3870.          * maxval!).
  3871.          */
  3872.         count = regrepeat(OPERAND(scan), maxval);
  3873.         if (got_int)
  3874.             return FALSE;
  3875.         if (minval <= maxval)
  3876.         {
  3877.             /* Range is the normal way around, use longest match */
  3878.             while (count >= minval)
  3879.             {
  3880.             /* If it could match, try it. */
  3881.             if (nextb == NUL || *reginput == nextb
  3882.                             || *reginput == nextb_ic)
  3883.             {
  3884.                 reg_save(&save);
  3885.                 if (regmatch(next))
  3886.                 return TRUE;
  3887.                 reg_restore(&save);
  3888.             }
  3889.             /* Couldn't or didn't match -- back up one char. */
  3890.             --count;
  3891.             if (reginput == regline && count >= minval)
  3892.             {
  3893.                 /* backup to last char of previous line */
  3894.                 --reglnum;
  3895.                 regline = reg_getline(reglnum);
  3896.                 reginput = regline + STRLEN(regline);
  3897.                 fast_breakcheck();
  3898.                 if (got_int)
  3899.                 return FALSE;
  3900.             }
  3901.             else
  3902.             {
  3903.                 --reginput;
  3904. #ifdef FEAT_MBYTE
  3905.                 if (has_mbyte)
  3906.                 reginput -= (*mb_head_off)(regline, reginput);
  3907. #endif
  3908.             }
  3909.             }
  3910.         }
  3911.         else
  3912.         {
  3913.             /* Range is backwards, use shortest match first.
  3914.              * Careful: maxval and minval are exchanged! */
  3915.             if (count < maxval)
  3916.             return FALSE;
  3917.             for (;;)
  3918.             {
  3919.             /* If it could work, try it. */
  3920.             if (nextb == NUL || *reginput == nextb
  3921.                             || *reginput == nextb_ic)
  3922.             {
  3923.                 reg_save(&save);
  3924.                 if (regmatch(next))
  3925.                 return TRUE;
  3926.                 reg_restore(&save);
  3927.             }
  3928.             /* Couldn't or didn't match: try advancing one char. */
  3929.             if (count == minval
  3930.                      || regrepeat(OPERAND(scan), 1L) == 0)
  3931.                 break;
  3932.             ++count;
  3933.             if (got_int)
  3934.                 return FALSE;
  3935.             }
  3936.         }
  3937.         return FALSE;
  3938.         }
  3939.         /* break; Not Reached */
  3940.  
  3941.       case NOMATCH:
  3942.         {
  3943.         regsave_T    save;
  3944.  
  3945.         /* If the operand matches, we fail.  Otherwise backup and
  3946.          * continue with the next item. */
  3947.         reg_save(&save);
  3948.         if (regmatch(OPERAND(scan)))
  3949.             return FALSE;
  3950.         reg_restore(&save);
  3951.         }
  3952.         break;
  3953.  
  3954.       case MATCH:
  3955.       case SUBPAT:
  3956.         {
  3957.         regsave_T    save;
  3958.  
  3959.         /* If the operand doesn't match, we fail.  Otherwise backup
  3960.          * and continue with the next item. */
  3961.         reg_save(&save);
  3962.         if (!regmatch(OPERAND(scan)))
  3963.             return FALSE;
  3964.         if (op == MATCH)        /* zero-width */
  3965.             reg_restore(&save);
  3966.         }
  3967.         break;
  3968.  
  3969.       case BEHIND:
  3970.       case NOBEHIND:
  3971.         {
  3972.         regsave_T    save_after, save_start;
  3973.         regsave_T    save_behind_pos;
  3974.         int        needmatch = (op == BEHIND);
  3975.         long        col;
  3976.  
  3977.         /*
  3978.          * Look back in the input of the operand matches or not. This
  3979.          * must be done at every position in the input and checking if
  3980.          * the match ends at the current position.
  3981.          * First check if the next item matches, that's probably
  3982.          * faster.
  3983.          */
  3984.         reg_save(&save_start);
  3985.         if (regmatch(next))
  3986.         {
  3987.             /* save the position after the found match for next */
  3988.             reg_save(&save_after);
  3989.  
  3990.             /* start looking for a match with operand at the current
  3991.              * postion.  Go back one character until we find the
  3992.              * result, hitting the start of the line or the previous
  3993.              * line (for multi-line matching).
  3994.              * Set behind_pos to where the match should end, BHPOS
  3995.              * will match it. */
  3996.             save_behind_pos = behind_pos;
  3997.             behind_pos = save_start;
  3998.             for (col = 0; ; ++col)
  3999.             {
  4000.             reg_restore(&save_start);
  4001.             if (regmatch(OPERAND(scan))
  4002.                 && reg_save_equal(&behind_pos))
  4003.             {
  4004.                 behind_pos = save_behind_pos;
  4005.                 /* found a match that ends where "next" started */
  4006.                 if (needmatch)
  4007.                 {
  4008.                 reg_restore(&save_after);
  4009.                 return TRUE;
  4010.                 }
  4011.                 return FALSE;
  4012.             }
  4013.             /*
  4014.              * No match: Go back one character.  May go to
  4015.              * previous line once.
  4016.              */
  4017.             if (REG_MULTI)
  4018.             {
  4019.                 if (save_start.rs_u.pos.col == 0)
  4020.                 {
  4021.                 if (save_start.rs_u.pos.lnum
  4022.                         < behind_pos.rs_u.pos.lnum
  4023.                     || reg_getline(
  4024.                         --save_start.rs_u.pos.lnum) == NULL)
  4025.                     break;
  4026.                 reg_restore(&save_start);
  4027.                 save_start.rs_u.pos.col =
  4028.                              (colnr_T)STRLEN(regline);
  4029.                 }
  4030.                 else
  4031.                 --save_start.rs_u.pos.col;
  4032.             }
  4033.             else
  4034.             {
  4035.                 if (save_start.rs_u.ptr == regline)
  4036.                 break;
  4037.                 --save_start.rs_u.ptr;
  4038.             }
  4039.             }
  4040.  
  4041.             /* NOBEHIND succeeds when no match was found */
  4042.             behind_pos = save_behind_pos;
  4043.             if (!needmatch)
  4044.             {
  4045.             reg_restore(&save_after);
  4046.             return TRUE;
  4047.             }
  4048.         }
  4049.         return FALSE;
  4050.         }
  4051.  
  4052.       case BHPOS:
  4053.         if (REG_MULTI)
  4054.         {
  4055.         if (behind_pos.rs_u.pos.col != (colnr_T)(reginput - regline)
  4056.             || behind_pos.rs_u.pos.lnum != reglnum)
  4057.             return FALSE;
  4058.         }
  4059.         else if (behind_pos.rs_u.ptr != reginput)
  4060.         return FALSE;
  4061.         break;
  4062.  
  4063.       case NEWL:
  4064.         if (c != NUL || reglnum == reg_maxline)
  4065.         return FALSE;
  4066.         reg_nextline();
  4067.         break;
  4068.  
  4069.       case END:
  4070.         return TRUE;    /* Success! */
  4071.  
  4072.       default:
  4073.         EMSG(_(e_re_corr));
  4074. #ifdef DEBUG
  4075.         printf("Illegal op code %d\n", op);
  4076. #endif
  4077.         return FALSE;
  4078.       }
  4079.     }
  4080.  
  4081.     scan = next;
  4082.     }
  4083.  
  4084.     /*
  4085.      * We get here only if there's trouble -- normally "case END" is the
  4086.      * terminating point.
  4087.      */
  4088.     EMSG(_(e_re_corr));
  4089. #ifdef DEBUG
  4090.     printf("Premature EOL\n");
  4091. #endif
  4092.     return FALSE;
  4093. }
  4094.  
  4095. #ifdef FEAT_MBYTE
  4096. # define ADVANCE_P(x) if (has_mbyte) x += (*mb_ptr2len_check)(x); else ++x
  4097. #else
  4098. # define ADVANCE_P(x) ++x
  4099. #endif
  4100.  
  4101. /*
  4102.  * regrepeat - repeatedly match something simple, return how many.
  4103.  * Advances reginput (and reglnum) to just after the matched chars.
  4104.  */
  4105.     static int
  4106. regrepeat(p, maxcount)
  4107.     char_u    *p;
  4108.     long    maxcount;   /* maximum number of matches allowed */
  4109. {
  4110.     long    count = 0;
  4111.     char_u    *scan;
  4112.     char_u    *opnd;
  4113.     int        mask;
  4114.     int        testval = 0;
  4115.  
  4116.     scan = reginput;        /* Make local copy of reginput for speed. */
  4117.     opnd = OPERAND(p);
  4118.     switch (OP(p))
  4119.     {
  4120.       case ANY:
  4121.       case ANY + ADD_NL:
  4122.     while (count < maxcount)
  4123.     {
  4124.         /* Matching anything means we continue until end-of-line (or
  4125.          * end-of-file for ANY + ADD_NL), only limited by maxcount. */
  4126.         while (*scan != NUL && count < maxcount)
  4127.         {
  4128.         ++count;
  4129.         ADVANCE_P(scan);
  4130.         }
  4131.         if (!WITH_NL(OP(p)) || reglnum == reg_maxline || count == maxcount)
  4132.         break;
  4133.         ++count;        /* count the line-break */
  4134.         reg_nextline();
  4135.         scan = reginput;
  4136.         if (got_int)
  4137.         break;
  4138.     }
  4139.     break;
  4140.  
  4141.       case IDENT:
  4142.       case IDENT + ADD_NL:
  4143.     testval = TRUE;
  4144.     /*FALLTHROUGH*/
  4145.       case SIDENT:
  4146.       case SIDENT + ADD_NL:
  4147.     while (count < maxcount)
  4148.     {
  4149.         if (vim_isIDc(*scan) && (testval || !isdigit(*scan)))
  4150.         ++scan;
  4151.         else if (*scan == NUL)
  4152.         {
  4153.         if (!WITH_NL(OP(p)) || reglnum == reg_maxline)
  4154.             break;
  4155.         reg_nextline();
  4156.         scan = reginput;
  4157.         if (got_int)
  4158.             break;
  4159.         }
  4160.         else
  4161.         break;
  4162.         ++count;
  4163.     }
  4164.     break;
  4165.  
  4166.       case KWORD:
  4167.       case KWORD + ADD_NL:
  4168.     testval = TRUE;
  4169.     /*FALLTHROUGH*/
  4170.       case SKWORD:
  4171.       case SKWORD + ADD_NL:
  4172.     while (count < maxcount)
  4173.     {
  4174.         if (vim_iswordp(scan) && (testval || !isdigit(*scan)))
  4175.         {
  4176.         ADVANCE_P(scan);
  4177.         }
  4178.         else if (*scan == NUL)
  4179.         {
  4180.         if (!WITH_NL(OP(p)) || reglnum == reg_maxline)
  4181.             break;
  4182.         reg_nextline();
  4183.         scan = reginput;
  4184.         if (got_int)
  4185.             break;
  4186.         }
  4187.         else
  4188.         break;
  4189.         ++count;
  4190.     }
  4191.     break;
  4192.  
  4193.       case FNAME:
  4194.       case FNAME + ADD_NL:
  4195.     testval = TRUE;
  4196.     /*FALLTHROUGH*/
  4197.       case SFNAME:
  4198.       case SFNAME + ADD_NL:
  4199.     while (count < maxcount)
  4200.     {
  4201.         if (vim_isfilec(*scan) && (testval || !isdigit(*scan)))
  4202.         {
  4203.         ADVANCE_P(scan);
  4204.         }
  4205.         else if (*scan == NUL)
  4206.         {
  4207.         if (!WITH_NL(OP(p)) || reglnum == reg_maxline)
  4208.             break;
  4209.         reg_nextline();
  4210.         scan = reginput;
  4211.         if (got_int)
  4212.             break;
  4213.         }
  4214.         else
  4215.         break;
  4216.         ++count;
  4217.     }
  4218.     break;
  4219.  
  4220.       case PRINT:
  4221.       case PRINT + ADD_NL:
  4222.     testval = TRUE;
  4223.     /*FALLTHROUGH*/
  4224.       case SPRINT:
  4225.       case SPRINT + ADD_NL:
  4226.     while (count < maxcount)
  4227.     {
  4228.         if (*scan == NUL)
  4229.         {
  4230.         if (!WITH_NL(OP(p)) || reglnum == reg_maxline)
  4231.             break;
  4232.         reg_nextline();
  4233.         scan = reginput;
  4234.         if (got_int)
  4235.             break;
  4236.         }
  4237.         else if (ptr2cells(scan) == 1 && (testval || !isdigit(*scan)))
  4238.         {
  4239.         ADVANCE_P(scan);
  4240.         }
  4241.         else
  4242.         break;
  4243.         ++count;
  4244.     }
  4245.     break;
  4246.  
  4247.       case WHITE:
  4248.       case WHITE + ADD_NL:
  4249.     testval = mask = RI_WHITE;
  4250. do_class:
  4251.     while (count < maxcount)
  4252.     {
  4253. #ifdef FEAT_MBYTE
  4254.         int        l;
  4255. #endif
  4256.         if (*scan == NUL)
  4257.         {
  4258.         if (!WITH_NL(OP(p)) || reglnum == reg_maxline)
  4259.             break;
  4260.         reg_nextline();
  4261.         scan = reginput;
  4262.         if (got_int)
  4263.             break;
  4264.         }
  4265. #ifdef FEAT_MBYTE
  4266.         else if (has_mbyte && (l = (*mb_ptr2len_check)(scan)) > 1)
  4267.         {
  4268.         if (testval != 0)
  4269.             break;
  4270.         scan += l;
  4271.         }
  4272. #endif
  4273.         else if ((class_tab[*scan] & mask) == testval)
  4274.         ++scan;
  4275.         else
  4276.         break;
  4277.         ++count;
  4278.     }
  4279.     break;
  4280.  
  4281.       case NWHITE:
  4282.       case NWHITE + ADD_NL:
  4283.     mask = RI_WHITE;
  4284.     goto do_class;
  4285.       case DIGIT:
  4286.       case DIGIT + ADD_NL:
  4287.     testval = mask = RI_DIGIT;
  4288.     goto do_class;
  4289.       case NDIGIT:
  4290.       case NDIGIT + ADD_NL:
  4291.     mask = RI_DIGIT;
  4292.     goto do_class;
  4293.       case HEX:
  4294.       case HEX + ADD_NL:
  4295.     testval = mask = RI_HEX;
  4296.     goto do_class;
  4297.       case NHEX:
  4298.       case NHEX + ADD_NL:
  4299.     mask = RI_HEX;
  4300.     goto do_class;
  4301.       case OCTAL:
  4302.       case OCTAL + ADD_NL:
  4303.     testval = mask = RI_OCTAL;
  4304.     goto do_class;
  4305.       case NOCTAL:
  4306.       case NOCTAL + ADD_NL:
  4307.     mask = RI_OCTAL;
  4308.     goto do_class;
  4309.       case WORD:
  4310.       case WORD + ADD_NL:
  4311.     testval = mask = RI_WORD;
  4312.     goto do_class;
  4313.       case NWORD:
  4314.       case NWORD + ADD_NL:
  4315.     mask = RI_WORD;
  4316.     goto do_class;
  4317.       case HEAD:
  4318.       case HEAD + ADD_NL:
  4319.     testval = mask = RI_HEAD;
  4320.     goto do_class;
  4321.       case NHEAD:
  4322.       case NHEAD + ADD_NL:
  4323.     mask = RI_HEAD;
  4324.     goto do_class;
  4325.       case ALPHA:
  4326.       case ALPHA + ADD_NL:
  4327.     testval = mask = RI_ALPHA;
  4328.     goto do_class;
  4329.       case NALPHA:
  4330.       case NALPHA + ADD_NL:
  4331.     mask = RI_ALPHA;
  4332.     goto do_class;
  4333.       case LOWER:
  4334.       case LOWER + ADD_NL:
  4335.     testval = mask = RI_LOWER;
  4336.     goto do_class;
  4337.       case NLOWER:
  4338.       case NLOWER + ADD_NL:
  4339.     mask = RI_LOWER;
  4340.     goto do_class;
  4341.       case UPPER:
  4342.       case UPPER + ADD_NL:
  4343.     testval = mask = RI_UPPER;
  4344.     goto do_class;
  4345.       case NUPPER:
  4346.       case NUPPER + ADD_NL:
  4347.     mask = RI_UPPER;
  4348.     goto do_class;
  4349.  
  4350.       case EXACTLY:
  4351.     {
  4352.         int        cu, cl;
  4353.  
  4354.         /* This doesn't do a multi-byte character, because a MULTIBYTECODE
  4355.          * would have been used for it. */
  4356.         if (ireg_ic)
  4357.         {
  4358.         cu = TO_UPPER(*opnd);
  4359.         cl = TO_LOWER(*opnd);
  4360.         while (count < maxcount && (*scan == cu || *scan == cl))
  4361.         {
  4362.             count++;
  4363.             scan++;
  4364.         }
  4365.         }
  4366.         else
  4367.         {
  4368.         cu = *opnd;
  4369.         while (count < maxcount && *scan == cu)
  4370.         {
  4371.             count++;
  4372.             scan++;
  4373.         }
  4374.         }
  4375.         break;
  4376.     }
  4377.  
  4378. #ifdef FEAT_MBYTE
  4379.       case MULTIBYTECODE:
  4380.     {
  4381.         int        i, len, cf = 0;
  4382.  
  4383.         /* Safety check (just in case 'encoding' was changed since
  4384.          * compiling the program). */
  4385.         if ((len = (*mb_ptr2len_check)(opnd)) > 1)
  4386.         {
  4387.         if (ireg_ic && enc_utf8)
  4388.             cf = utf_fold(utf_ptr2char(opnd));
  4389.         while (count < maxcount)
  4390.         {
  4391.             for (i = 0; i < len; ++i)
  4392.             if (opnd[i] != scan[i])
  4393.                 break;
  4394.             if (i < len && (!ireg_ic || !enc_utf8
  4395.                     || utf_fold(utf_ptr2char(scan)) != cf))
  4396.             break;
  4397.             scan += len;
  4398.             ++count;
  4399.         }
  4400.         }
  4401.     }
  4402.     break;
  4403. #endif
  4404.  
  4405.       case ANYOF:
  4406.       case ANYOF + ADD_NL:
  4407.     testval = TRUE;
  4408.     /*FALLTHROUGH*/
  4409.  
  4410.       case ANYBUT:
  4411.       case ANYBUT + ADD_NL:
  4412.     while (count < maxcount)
  4413.     {
  4414. #ifdef FEAT_MBYTE
  4415.         int len;
  4416. #endif
  4417.         if (*scan == NUL)
  4418.         {
  4419.         if (!WITH_NL(OP(p)) || reglnum == reg_maxline)
  4420.             break;
  4421.         reg_nextline();
  4422.         scan = reginput;
  4423.         if (got_int)
  4424.             break;
  4425.         }
  4426. #ifdef FEAT_MBYTE
  4427.         else if (has_mbyte && (len = (*mb_ptr2len_check)(scan)) > 1)
  4428.         {
  4429.         if ((cstrchr(opnd, (*mb_ptr2char)(scan)) == NULL) == testval)
  4430.             break;
  4431.         scan += len;
  4432.         }
  4433. #endif
  4434.         else
  4435.         {
  4436.         if ((cstrchr(opnd, *scan) == NULL) == testval)
  4437.             break;
  4438.         ++scan;
  4439.         }
  4440.         ++count;
  4441.     }
  4442.     break;
  4443.  
  4444.       case NEWL:
  4445.     while (count < maxcount && *scan == NUL && reglnum < reg_maxline)
  4446.     {
  4447.         count++;
  4448.         reg_nextline();
  4449.         scan = reginput;
  4450.         if (got_int)
  4451.         break;
  4452.     }
  4453.     break;
  4454.  
  4455.       default:            /* Oh dear.  Called inappropriately. */
  4456.     EMSG(_(e_re_corr));
  4457. #ifdef DEBUG
  4458.     printf("Called regrepeat with op code %d\n", OP(p));
  4459. #endif
  4460.     break;
  4461.     }
  4462.  
  4463.     reginput = scan;
  4464.  
  4465.     return (int)count;
  4466. }
  4467.  
  4468. /*
  4469.  * regnext - dig the "next" pointer out of a node
  4470.  */
  4471.     static char_u *
  4472. regnext(p)
  4473.     char_u  *p;
  4474. {
  4475.     int        offset;
  4476.  
  4477.     if (p == JUST_CALC_SIZE)
  4478.     return NULL;
  4479.  
  4480.     offset = NEXT(p);
  4481.     if (offset == 0)
  4482.     return NULL;
  4483.  
  4484.     if (OP(p) == BACK)
  4485.     return p - offset;
  4486.     else
  4487.     return p + offset;
  4488. }
  4489.  
  4490. /*
  4491.  * Check the regexp program for its magic number.
  4492.  * Return TRUE if it's wrong.
  4493.  */
  4494.     static int
  4495. prog_magic_wrong()
  4496. {
  4497.     if (UCHARAT(REG_MULTI
  4498.         ? reg_mmatch->regprog->program
  4499.         : reg_match->regprog->program) != REGMAGIC)
  4500.     {
  4501.     EMSG(_(e_re_corr));
  4502.     return TRUE;
  4503.     }
  4504.     return FALSE;
  4505. }
  4506.  
  4507. /*
  4508.  * Cleanup the subexpressions, if this wasn't done yet.
  4509.  * This construction is used to clear the subexpressions only when they are
  4510.  * used (to increase speed).
  4511.  */
  4512.     static void
  4513. cleanup_subexpr()
  4514. {
  4515.     if (need_clear_subexpr)
  4516.     {
  4517.     if (REG_MULTI)
  4518.     {
  4519.         /* Use 0xff to set lnum to -1 */
  4520.         vim_memset(reg_startpos, 0xff, sizeof(lpos_T) * NSUBEXP);
  4521.         vim_memset(reg_endpos, 0xff, sizeof(lpos_T) * NSUBEXP);
  4522.     }
  4523.     else
  4524.     {
  4525.         vim_memset(reg_startp, 0, sizeof(char_u *) * NSUBEXP);
  4526.         vim_memset(reg_endp, 0, sizeof(char_u *) * NSUBEXP);
  4527.     }
  4528.     need_clear_subexpr = FALSE;
  4529.     }
  4530. }
  4531.  
  4532. #ifdef FEAT_SYN_HL
  4533.     static void
  4534. cleanup_zsubexpr()
  4535. {
  4536.     if (need_clear_zsubexpr)
  4537.     {
  4538.     if (REG_MULTI)
  4539.     {
  4540.         /* Use 0xff to set lnum to -1 */
  4541.         vim_memset(reg_startzpos, 0xff, sizeof(lpos_T) * NSUBEXP);
  4542.         vim_memset(reg_endzpos, 0xff, sizeof(lpos_T) * NSUBEXP);
  4543.     }
  4544.     else
  4545.     {
  4546.         vim_memset(reg_startzp, 0, sizeof(char_u *) * NSUBEXP);
  4547.         vim_memset(reg_endzp, 0, sizeof(char_u *) * NSUBEXP);
  4548.     }
  4549.     need_clear_zsubexpr = FALSE;
  4550.     }
  4551. }
  4552. #endif
  4553.  
  4554. /*
  4555.  * Advance reglnum, regline and reginput to the next line.
  4556.  */
  4557.     static void
  4558. reg_nextline()
  4559. {
  4560.     regline = reg_getline(++reglnum);
  4561.     reginput = regline;
  4562.     fast_breakcheck();
  4563. }
  4564.  
  4565. /*
  4566.  * Save the input line and position in a regsave_T.
  4567.  */
  4568.     static void
  4569. reg_save(save)
  4570.     regsave_T    *save;
  4571. {
  4572.     if (REG_MULTI)
  4573.     {
  4574.     save->rs_u.pos.col = (colnr_T)(reginput - regline);
  4575.     save->rs_u.pos.lnum = reglnum;
  4576.     }
  4577.     else
  4578.     save->rs_u.ptr = reginput;
  4579. }
  4580.  
  4581. /*
  4582.  * Restore the input line and position from a regsave_T.
  4583.  */
  4584.     static void
  4585. reg_restore(save)
  4586.     regsave_T    *save;
  4587. {
  4588.     if (REG_MULTI)
  4589.     {
  4590.     if (reglnum != save->rs_u.pos.lnum)
  4591.     {
  4592.         /* only call reg_getline() when the line number changed to save
  4593.          * a bit of time */
  4594.         reglnum = save->rs_u.pos.lnum;
  4595.         regline = reg_getline(reglnum);
  4596.     }
  4597.     reginput = regline + save->rs_u.pos.col;
  4598.     }
  4599.     else
  4600.     reginput = save->rs_u.ptr;
  4601. }
  4602.  
  4603. /*
  4604.  * Return TRUE if current position is equal to saved position.
  4605.  */
  4606.     static int
  4607. reg_save_equal(save)
  4608.     regsave_T    *save;
  4609. {
  4610.     if (REG_MULTI)
  4611.     return reglnum == save->rs_u.pos.lnum
  4612.                   && reginput == regline + save->rs_u.pos.col;
  4613.     return reginput == save->rs_u.ptr;
  4614. }
  4615.  
  4616. /*
  4617.  * Tentatively set the sub-expression start to the current position (after
  4618.  * calling regmatch() they will have changed).  Need to save the existing
  4619.  * values for when there is no match.
  4620.  * Use pointer or position, depending on REG_MULTI.
  4621.  */
  4622.     static void
  4623. save_se(savep, posp, pp)
  4624.     save_se_T    *savep;
  4625.     lpos_T    *posp;
  4626.     char_u    **pp;
  4627. {
  4628.     if (REG_MULTI)
  4629.     {
  4630.     savep->se_u.pos = *posp;
  4631.     posp->lnum = reglnum;
  4632.     posp->col = (colnr_T)(reginput - regline);
  4633.     }
  4634.     else
  4635.     {
  4636.     savep->se_u.ptr = *pp;
  4637.     *pp = reginput;
  4638.     }
  4639. }
  4640.  
  4641. /*
  4642.  * We were wrong, restore the sub-expressions.
  4643.  */
  4644.     static void
  4645. restore_se(savep, posp, pp)
  4646.     save_se_T    *savep;
  4647.     lpos_T    *posp;
  4648.     char_u    **pp;
  4649. {
  4650.     if (REG_MULTI)
  4651.     *posp = savep->se_u.pos;
  4652.     else
  4653.     *pp = savep->se_u.ptr;
  4654. }
  4655.  
  4656. /*
  4657.  * Compare a number with the operand of RE_LNUM, RE_COL or RE_VCOL.
  4658.  */
  4659.     static int
  4660. re_num_cmp(val, scan)
  4661.     long_u    val;
  4662.     char_u    *scan;
  4663. {
  4664.     long_u  n = OPERAND_MIN(scan);
  4665.  
  4666.     if (OPERAND_CMP(scan) == '>')
  4667.     return val > n;
  4668.     if (OPERAND_CMP(scan) == '<')
  4669.     return val < n;
  4670.     return val == n;
  4671. }
  4672.  
  4673.  
  4674. #ifdef DEBUG
  4675.  
  4676. /*
  4677.  * regdump - dump a regexp onto stdout in vaguely comprehensible form
  4678.  */
  4679.     static void
  4680. regdump(pattern, r)
  4681.     char_u    *pattern;
  4682.     regprog_T    *r;
  4683. {
  4684.     char_u  *s;
  4685.     int        op = EXACTLY;    /* Arbitrary non-END op. */
  4686.     char_u  *next;
  4687.     char_u  *end = NULL;
  4688.  
  4689.     printf("\r\nregcomp(%s):\r\n", pattern);
  4690.  
  4691.     s = r->program + 1;
  4692.     /*
  4693.      * Loop until we find the END that isn't before a referred next (an END
  4694.      * can also appear in a NOMATCH operand).
  4695.      */
  4696.     while (op != END || s <= end)
  4697.     {
  4698.     op = OP(s);
  4699.     printf("%2d%s", (int)(s - r->program), regprop(s)); /* Where, what. */
  4700.     next = regnext(s);
  4701.     if (next == NULL)    /* Next ptr. */
  4702.         printf("(0)");
  4703.     else
  4704.         printf("(%d)", (int)((s - r->program) + (next - s)));
  4705.     if (end < next)
  4706.         end = next;
  4707.     if (op == BRACE_LIMITS)
  4708.     {
  4709.         /* Two short ints */
  4710.         printf(" minval %ld, maxval %ld", OPERAND_MIN(s), OPERAND_MAX(s));
  4711.         s += 8;
  4712.     }
  4713.     s += 3;
  4714.     if (op == ANYOF || op == ANYOF + ADD_NL
  4715.         || op == ANYBUT || op == ANYBUT + ADD_NL
  4716.         || op == EXACTLY)
  4717.     {
  4718.         /* Literal string, where present. */
  4719.         while (*s != NUL)
  4720.         printf("%c", *s++);
  4721.         s++;
  4722.     }
  4723.     printf("\r\n");
  4724.     }
  4725.  
  4726.     /* Header fields of interest. */
  4727.     if (r->regstart != NUL)
  4728.     printf("start `%s' 0x%x; ", r->regstart < 256
  4729.         ? (char *)transchar(r->regstart)
  4730.         : "multibyte", r->regstart);
  4731.     if (r->reganch)
  4732.     printf("anchored; ");
  4733.     if (r->regmust != NULL)
  4734.     printf("must have \"%s\"", r->regmust);
  4735.     printf("\r\n");
  4736. }
  4737.  
  4738. /*
  4739.  * regprop - printable representation of opcode
  4740.  */
  4741.     static char_u *
  4742. regprop(op)
  4743.     char_u       *op;
  4744. {
  4745.     char_u        *p;
  4746.     static char_u   buf[50];
  4747.  
  4748.     (void) strcpy(buf, ":");
  4749.  
  4750.     switch (OP(op))
  4751.     {
  4752.       case BOL:
  4753.     p = "BOL";
  4754.     break;
  4755.       case EOL:
  4756.     p = "EOL";
  4757.     break;
  4758.       case RE_BOF:
  4759.     p = "BOF";
  4760.     break;
  4761.       case RE_EOF:
  4762.     p = "EOF";
  4763.     break;
  4764.       case CURSOR:
  4765.     p = "CURSOR";
  4766.     break;
  4767.       case RE_LNUM:
  4768.     p = "RE_LNUM";
  4769.     break;
  4770.       case RE_COL:
  4771.     p = "RE_COL";
  4772.     break;
  4773.       case RE_VCOL:
  4774.     p = "RE_VCOL";
  4775.     break;
  4776.       case BOW:
  4777.     p = "BOW";
  4778.     break;
  4779.       case EOW:
  4780.     p = "EOW";
  4781.     break;
  4782.       case ANY:
  4783.     p = "ANY";
  4784.     break;
  4785.       case ANY + ADD_NL:
  4786.     p = "ANY+NL";
  4787.     break;
  4788.       case ANYOF:
  4789.     p = "ANYOF";
  4790.     break;
  4791.       case ANYOF + ADD_NL:
  4792.     p = "ANYOF+NL";
  4793.     break;
  4794.       case ANYBUT:
  4795.     p = "ANYBUT";
  4796.     break;
  4797.       case ANYBUT + ADD_NL:
  4798.     p = "ANYBUT+NL";
  4799.     break;
  4800.       case IDENT:
  4801.     p = "IDENT";
  4802.     break;
  4803.       case IDENT + ADD_NL:
  4804.     p = "IDENT+NL";
  4805.     break;
  4806.       case SIDENT:
  4807.     p = "SIDENT";
  4808.     break;
  4809.       case SIDENT + ADD_NL:
  4810.     p = "SIDENT+NL";
  4811.     break;
  4812.       case KWORD:
  4813.     p = "KWORD";
  4814.     break;
  4815.       case KWORD + ADD_NL:
  4816.     p = "KWORD+NL";
  4817.     break;
  4818.       case SKWORD:
  4819.     p = "SKWORD";
  4820.     break;
  4821.       case SKWORD + ADD_NL:
  4822.     p = "SKWORD+NL";
  4823.     break;
  4824.       case FNAME:
  4825.     p = "FNAME";
  4826.     break;
  4827.       case FNAME + ADD_NL:
  4828.     p = "FNAME+NL";
  4829.     break;
  4830.       case SFNAME:
  4831.     p = "SFNAME";
  4832.     break;
  4833.       case SFNAME + ADD_NL:
  4834.     p = "SFNAME+NL";
  4835.     break;
  4836.       case PRINT:
  4837.     p = "PRINT";
  4838.     break;
  4839.       case PRINT + ADD_NL:
  4840.     p = "PRINT+NL";
  4841.     break;
  4842.       case SPRINT:
  4843.     p = "SPRINT";
  4844.     break;
  4845.       case SPRINT + ADD_NL:
  4846.     p = "SPRINT+NL";
  4847.     break;
  4848.       case WHITE:
  4849.     p = "WHITE";
  4850.     break;
  4851.       case WHITE + ADD_NL:
  4852.     p = "WHITE+NL";
  4853.     break;
  4854.       case NWHITE:
  4855.     p = "NWHITE";
  4856.     break;
  4857.       case NWHITE + ADD_NL:
  4858.     p = "NWHITE+NL";
  4859.     break;
  4860.       case DIGIT:
  4861.     p = "DIGIT";
  4862.     break;
  4863.       case DIGIT + ADD_NL:
  4864.     p = "DIGIT+NL";
  4865.     break;
  4866.       case NDIGIT:
  4867.     p = "NDIGIT";
  4868.     break;
  4869.       case NDIGIT + ADD_NL:
  4870.     p = "NDIGIT+NL";
  4871.     break;
  4872.       case HEX:
  4873.     p = "HEX";
  4874.     break;
  4875.       case HEX + ADD_NL:
  4876.     p = "HEX+NL";
  4877.     break;
  4878.       case NHEX:
  4879.     p = "NHEX";
  4880.     break;
  4881.       case NHEX + ADD_NL:
  4882.     p = "NHEX+NL";
  4883.     break;
  4884.       case OCTAL:
  4885.     p = "OCTAL";
  4886.     break;
  4887.       case OCTAL + ADD_NL:
  4888.     p = "OCTAL+NL";
  4889.     break;
  4890.       case NOCTAL:
  4891.     p = "NOCTAL";
  4892.     break;
  4893.       case NOCTAL + ADD_NL:
  4894.     p = "NOCTAL+NL";
  4895.     break;
  4896.       case WORD:
  4897.     p = "WORD";
  4898.     break;
  4899.       case WORD + ADD_NL:
  4900.     p = "WORD+NL";
  4901.     break;
  4902.       case NWORD:
  4903.     p = "NWORD";
  4904.     break;
  4905.       case NWORD + ADD_NL:
  4906.     p = "NWORD+NL";
  4907.     break;
  4908.       case HEAD:
  4909.     p = "HEAD";
  4910.     break;
  4911.       case HEAD + ADD_NL:
  4912.     p = "HEAD+NL";
  4913.     break;
  4914.       case NHEAD:
  4915.     p = "NHEAD";
  4916.     break;
  4917.       case NHEAD + ADD_NL:
  4918.     p = "NHEAD+NL";
  4919.     break;
  4920.       case ALPHA:
  4921.     p = "ALPHA";
  4922.     break;
  4923.       case ALPHA + ADD_NL:
  4924.     p = "ALPHA+NL";
  4925.     break;
  4926.       case NALPHA:
  4927.     p = "NALPHA";
  4928.     break;
  4929.       case NALPHA + ADD_NL:
  4930.     p = "NALPHA+NL";
  4931.     break;
  4932.       case LOWER:
  4933.     p = "LOWER";
  4934.     break;
  4935.       case LOWER + ADD_NL:
  4936.     p = "LOWER+NL";
  4937.     break;
  4938.       case NLOWER:
  4939.     p = "NLOWER";
  4940.     break;
  4941.       case NLOWER + ADD_NL:
  4942.     p = "NLOWER+NL";
  4943.     break;
  4944.       case UPPER:
  4945.     p = "UPPER";
  4946.     break;
  4947.       case UPPER + ADD_NL:
  4948.     p = "UPPER+NL";
  4949.     break;
  4950.       case NUPPER:
  4951.     p = "NUPPER";
  4952.     break;
  4953.       case NUPPER + ADD_NL:
  4954.     p = "NUPPER+NL";
  4955.     break;
  4956.       case BRANCH:
  4957.     p = "BRANCH";
  4958.     break;
  4959.       case EXACTLY:
  4960.     p = "EXACTLY";
  4961.     break;
  4962.       case NOTHING:
  4963.     p = "NOTHING";
  4964.     break;
  4965.       case BACK:
  4966.     p = "BACK";
  4967.     break;
  4968.       case END:
  4969.     p = "END";
  4970.     break;
  4971.       case MOPEN + 0:
  4972.     p = "MATCH START";
  4973.     break;
  4974.       case MOPEN + 1:
  4975.       case MOPEN + 2:
  4976.       case MOPEN + 3:
  4977.       case MOPEN + 4:
  4978.       case MOPEN + 5:
  4979.       case MOPEN + 6:
  4980.       case MOPEN + 7:
  4981.       case MOPEN + 8:
  4982.       case MOPEN + 9:
  4983.     sprintf(buf + STRLEN(buf), "MOPEN%d", OP(op) - MOPEN);
  4984.     p = NULL;
  4985.     break;
  4986.       case MCLOSE + 0:
  4987.     p = "MATCH END";
  4988.     break;
  4989.       case MCLOSE + 1:
  4990.       case MCLOSE + 2:
  4991.       case MCLOSE + 3:
  4992.       case MCLOSE + 4:
  4993.       case MCLOSE + 5:
  4994.       case MCLOSE + 6:
  4995.       case MCLOSE + 7:
  4996.       case MCLOSE + 8:
  4997.       case MCLOSE + 9:
  4998.     sprintf(buf + STRLEN(buf), "MCLOSE%d", OP(op) - MCLOSE);
  4999.     p = NULL;
  5000.     break;
  5001.       case BACKREF + 1:
  5002.       case BACKREF + 2:
  5003.       case BACKREF + 3:
  5004.       case BACKREF + 4:
  5005.       case BACKREF + 5:
  5006.       case BACKREF + 6:
  5007.       case BACKREF + 7:
  5008.       case BACKREF + 8:
  5009.       case BACKREF + 9:
  5010.     sprintf(buf + STRLEN(buf), "BACKREF%d", OP(op) - BACKREF);
  5011.     p = NULL;
  5012.     break;
  5013.       case NOPEN:
  5014.     p = "NOPEN";
  5015.     break;
  5016.       case NCLOSE:
  5017.     p = "NCLOSE";
  5018.     break;
  5019. #ifdef FEAT_SYN_HL
  5020.       case ZOPEN + 1:
  5021.       case ZOPEN + 2:
  5022.       case ZOPEN + 3:
  5023.       case ZOPEN + 4:
  5024.       case ZOPEN + 5:
  5025.       case ZOPEN + 6:
  5026.       case ZOPEN + 7:
  5027.       case ZOPEN + 8:
  5028.       case ZOPEN + 9:
  5029.     sprintf(buf + STRLEN(buf), "ZOPEN%d", OP(op) - ZOPEN);
  5030.     p = NULL;
  5031.     break;
  5032.       case ZCLOSE + 1:
  5033.       case ZCLOSE + 2:
  5034.       case ZCLOSE + 3:
  5035.       case ZCLOSE + 4:
  5036.       case ZCLOSE + 5:
  5037.       case ZCLOSE + 6:
  5038.       case ZCLOSE + 7:
  5039.       case ZCLOSE + 8:
  5040.       case ZCLOSE + 9:
  5041.     sprintf(buf + STRLEN(buf), "ZCLOSE%d", OP(op) - ZCLOSE);
  5042.     p = NULL;
  5043.     break;
  5044.       case ZREF + 1:
  5045.       case ZREF + 2:
  5046.       case ZREF + 3:
  5047.       case ZREF + 4:
  5048.       case ZREF + 5:
  5049.       case ZREF + 6:
  5050.       case ZREF + 7:
  5051.       case ZREF + 8:
  5052.       case ZREF + 9:
  5053.     sprintf(buf + STRLEN(buf), "ZREF%d", OP(op) - ZREF);
  5054.     p = NULL;
  5055.     break;
  5056. #endif
  5057.       case STAR:
  5058.     p = "STAR";
  5059.     break;
  5060.       case PLUS:
  5061.     p = "PLUS";
  5062.     break;
  5063.       case NOMATCH:
  5064.     p = "NOMATCH";
  5065.     break;
  5066.       case MATCH:
  5067.     p = "MATCH";
  5068.     break;
  5069.       case BEHIND:
  5070.     p = "BEHIND";
  5071.     break;
  5072.       case NOBEHIND:
  5073.     p = "NOBEHIND";
  5074.     break;
  5075.       case SUBPAT:
  5076.     p = "SUBPAT";
  5077.     break;
  5078.       case BRACE_LIMITS:
  5079.     p = "BRACE_LIMITS";
  5080.     break;
  5081.       case BRACE_SIMPLE:
  5082.     p = "BRACE_SIMPLE";
  5083.     break;
  5084.       case BRACE_COMPLEX + 0:
  5085.       case BRACE_COMPLEX + 1:
  5086.       case BRACE_COMPLEX + 2:
  5087.       case BRACE_COMPLEX + 3:
  5088.       case BRACE_COMPLEX + 4:
  5089.       case BRACE_COMPLEX + 5:
  5090.       case BRACE_COMPLEX + 6:
  5091.       case BRACE_COMPLEX + 7:
  5092.       case BRACE_COMPLEX + 8:
  5093.       case BRACE_COMPLEX + 9:
  5094.     sprintf(buf + STRLEN(buf), "BRACE_COMPLEX%d", OP(op) - BRACE_COMPLEX);
  5095.     p = NULL;
  5096.     break;
  5097. #ifdef FEAT_MBYTE
  5098.       case MULTIBYTECODE:
  5099.     p = "MULTIBYTECODE";
  5100.     break;
  5101. #endif
  5102.       case NEWL:
  5103.     p = "NEWL";
  5104.     break;
  5105.       default:
  5106.     sprintf(buf + STRLEN(buf), "corrupt %d", OP(op));
  5107.     p = NULL;
  5108.     break;
  5109.     }
  5110.     if (p != NULL)
  5111.     (void) strcat(buf, p);
  5112.     return buf;
  5113. }
  5114. #endif
  5115.  
  5116. /*
  5117.  * Compare two strings, ignore case if ireg_ic set.
  5118.  * Return 0 if strings match, non-zero otherwise.
  5119.  */
  5120.     static int
  5121. cstrncmp(s1, s2, n)
  5122.     char_u    *s1, *s2;
  5123.     int        n;
  5124. {
  5125.     if (!ireg_ic)
  5126.     return STRNCMP(s1, s2, n);
  5127.     return MB_STRNICMP(s1, s2, n);
  5128. }
  5129.  
  5130. /*
  5131.  * cstrchr: This function is used a lot for simple searches, keep it fast!
  5132.  */
  5133.     static char_u *
  5134. cstrchr(s, c)
  5135.     char_u    *s;
  5136.     int        c;
  5137. {
  5138.     char_u    *p;
  5139.     int        cc;
  5140.  
  5141.     if (!ireg_ic
  5142. #ifdef FEAT_MBYTE
  5143.         || (!enc_utf8 && mb_char2len(c) > 1)
  5144. #endif
  5145.         )
  5146.     return vim_strchr(s, c);
  5147.  
  5148.     /* tolower() and toupper() can be slow, comparing twice should be a lot
  5149.      * faster (esp. when using MS Visual C++!).
  5150.      * For UTF-8 need to use folded case. */
  5151. #ifdef FEAT_MBYTE
  5152.     if (enc_utf8 && c > 0x80)
  5153.     cc = utf_fold(c);
  5154.     else
  5155. #endif
  5156.      if (isupper(c))
  5157.     cc = TO_LOWER(c);
  5158.     else if (islower(c))
  5159.     cc = TO_UPPER(c);
  5160.     else
  5161.     return vim_strchr(s, c);
  5162.  
  5163. #ifdef FEAT_MBYTE
  5164.     if (has_mbyte)
  5165.     {
  5166.     for (p = s; *p != NUL; p += (*mb_ptr2len_check)(p))
  5167.     {
  5168.         if (enc_utf8 && c > 0x80)
  5169.         {
  5170.         if (utf_fold(utf_ptr2char(p)) == cc)
  5171.             return p;
  5172.         }
  5173.         else if (*p == c || *p == cc)
  5174.         return p;
  5175.     }
  5176.     }
  5177.     else
  5178. #endif
  5179.     /* Faster version for when there are no multi-byte characters. */
  5180.     for (p = s; *p != NUL; ++p)
  5181.         if (*p == c || *p == cc)
  5182.         return p;
  5183.  
  5184.     return NULL;
  5185. }
  5186.  
  5187. /***************************************************************
  5188.  *              regsub stuff                   *
  5189.  ***************************************************************/
  5190.  
  5191. /* This stuff below really confuses cc on an SGI -- webb */
  5192. #ifdef __sgi
  5193. # undef __ARGS
  5194. # define __ARGS(x)  ()
  5195. #endif
  5196.  
  5197. /*
  5198.  * We should define ftpr as a pointer to a function returning a pointer to
  5199.  * a function returning a pointer to a function ...
  5200.  * This is impossible, so we declare a pointer to a function returning a
  5201.  * pointer to a function returning void. This should work for all compilers.
  5202.  */
  5203. typedef void (*(*fptr) __ARGS((char_u *, int)))();
  5204.  
  5205. static fptr do_upper __ARGS((char_u *, int));
  5206. static fptr do_Upper __ARGS((char_u *, int));
  5207. static fptr do_lower __ARGS((char_u *, int));
  5208. static fptr do_Lower __ARGS((char_u *, int));
  5209.  
  5210. static int vim_regsub_both __ARGS((char_u *source, char_u *dest, int copy, int magic, int backslash));
  5211.  
  5212.     static fptr
  5213. do_upper(d, c)
  5214.     char_u *d;
  5215.     int c;
  5216. {
  5217.     *d = TO_UPPER(c);
  5218.  
  5219.     return (fptr)NULL;
  5220. }
  5221.  
  5222.     static fptr
  5223. do_Upper(d, c)
  5224.     char_u *d;
  5225.     int c;
  5226. {
  5227.     *d = TO_UPPER(c);
  5228.  
  5229.     return (fptr)do_Upper;
  5230. }
  5231.  
  5232.     static fptr
  5233. do_lower(d, c)
  5234.     char_u *d;
  5235.     int c;
  5236. {
  5237.     *d = TO_LOWER(c);
  5238.  
  5239.     return (fptr)NULL;
  5240. }
  5241.  
  5242.     static fptr
  5243. do_Lower(d, c)
  5244.     char_u    *d;
  5245.     int        c;
  5246. {
  5247.     *d = TO_LOWER(c);
  5248.  
  5249.     return (fptr)do_Lower;
  5250. }
  5251.  
  5252. /*
  5253.  * regtilde(): Replace tildes in the pattern by the old pattern.
  5254.  *
  5255.  * Short explanation of the tilde: It stands for the previous replacement
  5256.  * pattern.  If that previous pattern also contains a ~ we should go back a
  5257.  * step further...  But we insert the previous pattern into the current one
  5258.  * and remember that.
  5259.  * This still does not handle the case where "magic" changes. TODO?
  5260.  *
  5261.  * The tildes are parsed once before the first call to vim_regsub().
  5262.  */
  5263.     char_u *
  5264. regtilde(source, magic)
  5265.     char_u    *source;
  5266.     int        magic;
  5267. {
  5268.     char_u    *newsub = source;
  5269.     char_u    *tmpsub;
  5270.     char_u    *p;
  5271.     int        len;
  5272.     int        prevlen;
  5273.  
  5274.     for (p = newsub; *p; ++p)
  5275.     {
  5276.     if ((*p == '~' && magic) || (*p == '\\' && *(p + 1) == '~' && !magic))
  5277.     {
  5278.         if (reg_prev_sub != NULL)
  5279.         {
  5280.         /* length = len(newsub) - 1 + len(prev_sub) + 1 */
  5281.         prevlen = (int)STRLEN(reg_prev_sub);
  5282.         tmpsub = alloc((unsigned)(STRLEN(newsub) + prevlen));
  5283.         if (tmpsub != NULL)
  5284.         {
  5285.             /* copy prefix */
  5286.             len = (int)(p - newsub);    /* not including ~ */
  5287.             mch_memmove(tmpsub, newsub, (size_t)len);
  5288.             /* interpretate tilde */
  5289.             mch_memmove(tmpsub + len, reg_prev_sub, (size_t)prevlen);
  5290.             /* copy postfix */
  5291.             if (!magic)
  5292.             ++p;            /* back off \ */
  5293.             STRCPY(tmpsub + len + prevlen, p + 1);
  5294.  
  5295.             if (newsub != source)    /* already allocated newsub */
  5296.             vim_free(newsub);
  5297.             newsub = tmpsub;
  5298.             p = newsub + len + prevlen;
  5299.         }
  5300.         }
  5301.         else if (magic)
  5302.         STRCPY(p, p + 1);        /* remove '~' */
  5303.         else
  5304.         STRCPY(p, p + 2);        /* remove '\~' */
  5305.         --p;
  5306.     }
  5307.     else if (*p == '\\' && p[1])        /* skip escaped characters */
  5308.         ++p;
  5309.     }
  5310.  
  5311.     vim_free(reg_prev_sub);
  5312.     if (newsub != source)    /* newsub was allocated, just keep it */
  5313.     reg_prev_sub = newsub;
  5314.     else            /* no ~ found, need to save newsub  */
  5315.     reg_prev_sub = vim_strsave(newsub);
  5316.     return newsub;
  5317. }
  5318.  
  5319. #ifdef FEAT_EVAL
  5320. static int can_f_submatch = FALSE;    /* TRUE when submatch() can be used */
  5321. #endif
  5322.  
  5323. #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
  5324. /*
  5325.  * vim_regsub() - perform substitutions after a vim_regexec() or
  5326.  * vim_regexec_multi() match.
  5327.  *
  5328.  * If "copy" is TRUE really copy into "dest".
  5329.  * If "copy" is FALSE nothing is copied, this is just to find out the length
  5330.  * of the result.
  5331.  *
  5332.  * If "backslash" is TRUE, a backslash will be removed later, need to double
  5333.  * them to keep them, and insert a backslash before a CR to avoid it being
  5334.  * replaced with a line break later.
  5335.  *
  5336.  * Note: The matched text must not change between the call of
  5337.  * vim_regexec()/vim_regexec_multi() and vim_regsub()!  It would make the back
  5338.  * references invalid!
  5339.  *
  5340.  * Returns the size of the replacement, including terminating NUL.
  5341.  */
  5342.     int
  5343. vim_regsub(rmp, source, dest, copy, magic, backslash)
  5344.     regmatch_T    *rmp;
  5345.     char_u    *source;
  5346.     char_u    *dest;
  5347.     int        copy;
  5348.     int        magic;
  5349.     int        backslash;
  5350. {
  5351.     reg_match = rmp;
  5352.     reg_mmatch = NULL;
  5353.     reg_maxline = 0;
  5354.     return vim_regsub_both(source, dest, copy, magic, backslash);
  5355. }
  5356. #endif
  5357.  
  5358.     int
  5359. vim_regsub_multi(rmp, lnum, source, dest, copy, magic, backslash)
  5360.     regmmatch_T    *rmp;
  5361.     linenr_T    lnum;
  5362.     char_u    *source;
  5363.     char_u    *dest;
  5364.     int        copy;
  5365.     int        magic;
  5366.     int        backslash;
  5367. {
  5368.     reg_match = NULL;
  5369.     reg_mmatch = rmp;
  5370.     reg_buf = curbuf;        /* always works on the current buffer! */
  5371.     reg_firstlnum = lnum;
  5372.     reg_maxline = curbuf->b_ml.ml_line_count - lnum;
  5373.     return vim_regsub_both(source, dest, copy, magic, backslash);
  5374. }
  5375.  
  5376.     static int
  5377. vim_regsub_both(source, dest, copy, magic, backslash)
  5378.     char_u    *source;
  5379.     char_u    *dest;
  5380.     int        copy;
  5381.     int        magic;
  5382.     int        backslash;
  5383. {
  5384.     char_u    *src;
  5385.     char_u    *dst;
  5386.     char_u    *s;
  5387.     int        c;
  5388.     int        no = -1;
  5389.     fptr    func = (fptr)NULL;
  5390.     linenr_T    clnum = 0;    /* init for GCC */
  5391.     int        len = 0;    /* init for GCC */
  5392. #ifdef FEAT_EVAL
  5393.     static char_u *eval_result = NULL;
  5394. #endif
  5395.  
  5396.     /* Be paranoid... */
  5397.     if (source == NULL || dest == NULL)
  5398.     {
  5399.     EMSG(_(e_null));
  5400.     return 0;
  5401.     }
  5402.     if (prog_magic_wrong())
  5403.     return 0;
  5404.     src = source;
  5405.     dst = dest;
  5406.  
  5407.     /*
  5408.      * When the substitute part starts with "\=" evaluate it as an expression.
  5409.      */
  5410.     if (source[0] == '\\' && source[1] == '=')
  5411.     {
  5412. #ifdef FEAT_EVAL
  5413.     /* To make sure that the length doesn't change between checking the
  5414.      * length and copying the string, and to speed up things, the
  5415.      * resulting string is saved from the call with "copy" == FALSE to the
  5416.      * call with "copy" == TRUE. */
  5417.     if (copy)
  5418.     {
  5419.         if (eval_result != NULL)
  5420.         {
  5421.         STRCPY(dest, eval_result);
  5422.         dst += STRLEN(eval_result);
  5423.         vim_free(eval_result);
  5424.         eval_result = NULL;
  5425.         }
  5426.     }
  5427.     else
  5428.     {
  5429.         vim_free(eval_result);
  5430.         can_f_submatch = TRUE;
  5431.         eval_result = eval_to_string(source + 2, NULL);
  5432.         can_f_submatch = FALSE;
  5433.         if (eval_result != NULL)
  5434.         dst += STRLEN(eval_result);
  5435.     }
  5436. #endif
  5437.     }
  5438.     else
  5439.       while ((c = *src++) != NUL)
  5440.       {
  5441.     if (c == '&' && magic)
  5442.         no = 0;
  5443.     else if (c == '\\' && *src != NUL)
  5444.     {
  5445.         if (*src == '&' && !magic)
  5446.         {
  5447.         ++src;
  5448.         no = 0;
  5449.         }
  5450.         else if ('0' <= *src && *src <= '9')
  5451.         {
  5452.         no = *src++ - '0';
  5453.         }
  5454.         else if (vim_strchr((char_u *)"uUlLeE", *src))
  5455.         {
  5456.         switch (*src++)
  5457.         {
  5458.         case 'u':   func = (fptr)do_upper;
  5459.                 continue;
  5460.         case 'U':   func = (fptr)do_Upper;
  5461.                 continue;
  5462.         case 'l':   func = (fptr)do_lower;
  5463.                 continue;
  5464.         case 'L':   func = (fptr)do_Lower;
  5465.                 continue;
  5466.         case 'e':
  5467.         case 'E':   func = (fptr)NULL;
  5468.                 continue;
  5469.         }
  5470.         }
  5471.     }
  5472.     if (no < 0)          /* Ordinary character. */
  5473.     {
  5474. #ifdef FEAT_MBYTE
  5475.         int l;
  5476. #endif
  5477.  
  5478.         if (c == '\\' && *src != NUL)
  5479.         {
  5480.         /* Check for abbreviations -- webb */
  5481.         switch (*src)
  5482.         {
  5483.             case 'r':    c = CR;        ++src;    break;
  5484.             case 'n':    c = NL;        ++src;    break;
  5485.             case 't':    c = TAB;    ++src;    break;
  5486.          /* Oh no!  \e already has meaning in subst pat :-( */
  5487.          /* case 'e':   c = ESC;    ++src;    break; */
  5488.             case 'b':    c = Ctrl_H;    ++src;    break;
  5489.  
  5490.             /* If "backslash" is TRUE the backslash will be removed
  5491.              * later.  Used to insert a literal CR. */
  5492.             default:    if (backslash)
  5493.                 {
  5494.                     if (copy)
  5495.                     *dst = '\\';
  5496.                     ++dst;
  5497.                 }
  5498.                 c = *src++;
  5499.         }
  5500.         }
  5501.  
  5502.         /* Write to buffer, if copy is set. */
  5503. #ifdef FEAT_MBYTE
  5504.         if (has_mbyte && (l = (*mb_ptr2len_check)(src - 1)) > 1)
  5505.         {
  5506.         /* TODO: should use "func" here. */
  5507.         if (copy)
  5508.             mch_memmove(dst, src - 1, l);
  5509.         dst += l - 1;
  5510.         src += l - 1;
  5511.         }
  5512.         else
  5513.         {
  5514. #endif
  5515.         if (copy)
  5516.         {
  5517.             if (func == (fptr)NULL)    /* just copy */
  5518.             *dst = c;
  5519.             else            /* change case */
  5520.             func = (fptr)(func(dst, c));
  5521.             /* Turbo C complains without the typecast */
  5522.         }
  5523. #ifdef FEAT_MBYTE
  5524.         }
  5525. #endif
  5526.         dst++;
  5527.     }
  5528.     else
  5529.     {
  5530.         if (REG_MULTI)
  5531.         {
  5532.         clnum = reg_mmatch->startpos[no].lnum;
  5533.         if (clnum < 0 || reg_mmatch->endpos[no].lnum < 0)
  5534.             s = NULL;
  5535.         else
  5536.         {
  5537.             s = reg_getline(clnum) + reg_mmatch->startpos[no].col;
  5538.             if (reg_mmatch->endpos[no].lnum == clnum)
  5539.             len = reg_mmatch->endpos[no].col
  5540.                            - reg_mmatch->startpos[no].col;
  5541.             else
  5542.             len = (int)STRLEN(s);
  5543.         }
  5544.         }
  5545.         else
  5546.         {
  5547.         s = reg_match->startp[no];
  5548.         if (reg_match->endp[no] == NULL)
  5549.             s = NULL;
  5550.         else
  5551.             len = (int)(reg_match->endp[no] - s);
  5552.         }
  5553.         if (s != NULL)
  5554.         {
  5555.         for (;;)
  5556.         {
  5557.             if (len == 0)
  5558.             {
  5559.             if (REG_MULTI)
  5560.             {
  5561.                 if (reg_mmatch->endpos[no].lnum == clnum)
  5562.                 break;
  5563.                 if (copy)
  5564.                 *dst = CR;
  5565.                 ++dst;
  5566.                 s = reg_getline(++clnum);
  5567.                 if (reg_mmatch->endpos[no].lnum == clnum)
  5568.                 len = reg_mmatch->endpos[no].col;
  5569.                 else
  5570.                 len = (int)STRLEN(s);
  5571.             }
  5572.             else
  5573.                 break;
  5574.             }
  5575.             else if (*s == NUL) /* we hit NUL. */
  5576.             {
  5577.             if (copy)
  5578.                 EMSG(_(e_re_damg));
  5579.             goto exit;
  5580.             }
  5581.             else
  5582.             {
  5583.             if (backslash && (*s == CR || *s == '\\'))
  5584.             {
  5585.                 /*
  5586.                  * Insert a backslash in front of a CR, otherwise
  5587.                  * it will be replaced by a line break.
  5588.                  * Number of backslashes will be halved later,
  5589.                  * double them here.
  5590.                  */
  5591.                 if (copy)
  5592.                 {
  5593.                 dst[0] = '\\';
  5594.                 dst[1] = *s;
  5595.                 }
  5596.                 dst += 2;
  5597.             }
  5598.             else
  5599.             {
  5600.                 if (copy)
  5601.                 {
  5602.                 if (func == (fptr)NULL)        /* just copy */
  5603.                     *dst = *s;
  5604.                 else                /* change case */
  5605.                     func = (fptr)(func(dst, *s));
  5606.                 /* Turbo C complains without the typecast */
  5607.                 }
  5608.                 ++dst;
  5609.             }
  5610.             ++s;
  5611.             --len;
  5612.             }
  5613.         }
  5614.         }
  5615.         no = -1;
  5616.     }
  5617.       }
  5618.     if (copy)
  5619.     *dst = NUL;
  5620.  
  5621. exit:
  5622.     return (int)((dst - dest) + 1);
  5623. }
  5624.  
  5625. #ifdef FEAT_EVAL
  5626. /*
  5627.  * Used for the submatch() function: get the string from tne n'th submatch in
  5628.  * allocated memory.
  5629.  * Returns NULL when not in a ":s" command and for a non-existing submatch.
  5630.  */
  5631.     char_u *
  5632. reg_submatch(no)
  5633.     int        no;
  5634. {
  5635.     char_u    *retval = NULL;
  5636.     char_u    *s;
  5637.     int        len;
  5638.     int        round;
  5639.     linenr_T    lnum;
  5640.  
  5641.     if (!can_f_submatch)
  5642.     return NULL;
  5643.  
  5644.     if (REG_MULTI)
  5645.     {
  5646.     /*
  5647.      * First round: compute the length and allocate memory.
  5648.      * Second round: copy the text.
  5649.      */
  5650.     for (round = 1; round <= 2; ++round)
  5651.     {
  5652.         lnum = reg_mmatch->startpos[no].lnum;
  5653.         if (lnum < 0 || reg_mmatch->endpos[no].lnum < 0)
  5654.         return NULL;
  5655.  
  5656.         s = reg_getline(lnum) + reg_mmatch->startpos[no].col;
  5657.         if (reg_mmatch->endpos[no].lnum == lnum)
  5658.         {
  5659.         /* Within one line: take form start to end col. */
  5660.         len = reg_mmatch->endpos[no].col - reg_mmatch->startpos[no].col;
  5661.         if (round == 2)
  5662.         {
  5663.             STRNCPY(retval, s, len);
  5664.             retval[len] = NUL;
  5665.         }
  5666.         ++len;
  5667.         }
  5668.         else
  5669.         {
  5670.         /* Multiple lines: take start line from start col, middle
  5671.          * lines completely and end line up to end col. */
  5672.         len = (int)STRLEN(s);
  5673.         if (round == 2)
  5674.         {
  5675.             STRCPY(retval, s);
  5676.             retval[len] = '\r';
  5677.         }
  5678.         ++len;
  5679.         ++lnum;
  5680.         while (lnum < reg_mmatch->endpos[no].lnum)
  5681.         {
  5682.             s = reg_getline(lnum++);
  5683.             if (round == 2)
  5684.             STRCPY(retval + len, s);
  5685.             len += (int)STRLEN(s);
  5686.             if (round == 2)
  5687.             retval[len] = '\r';
  5688.             ++len;
  5689.         }
  5690.         if (round == 2)
  5691.             STRNCPY(retval + len, reg_getline(lnum),
  5692.                           reg_mmatch->endpos[no].col);
  5693.         len += reg_mmatch->endpos[no].col;
  5694.         if (round == 2)
  5695.             retval[len] = NUL;
  5696.         ++len;
  5697.         }
  5698.  
  5699.         if (round == 1)
  5700.         {
  5701.         retval = lalloc((long_u)len, TRUE);
  5702.         if (s == NULL)
  5703.             return NULL;
  5704.         }
  5705.     }
  5706.     }
  5707.     else
  5708.     {
  5709.     if (reg_match->endp[no] == NULL)
  5710.         retval = NULL;
  5711.     else
  5712.     {
  5713.         s = reg_match->startp[no];
  5714.         retval = vim_strnsave(s, (int)(reg_match->endp[no] - s));
  5715.     }
  5716.     }
  5717.  
  5718.     return retval;
  5719. }
  5720. #endif
  5721.